Coverage for sources/appcore/inscription.py: 99%
123 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-10-27 19:39 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-10-27 19:39 +0000
1# vim: set filetype=python fileencoding=utf-8:
2# -*- coding: utf-8 -*-
4#============================================================================#
5# #
6# Licensed under the Apache License, Version 2.0 (the "License"); #
7# you may not use this file except in compliance with the License. #
8# You may obtain a copy of the License at #
9# #
10# http://www.apache.org/licenses/LICENSE-2.0 #
11# #
12# Unless required by applicable law or agreed to in writing, software #
13# distributed under the License is distributed on an "AS IS" BASIS, #
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
15# See the License for the specific language governing permissions and #
16# limitations under the License. #
17# #
18#============================================================================#
21''' Application inscription management.
23 Logging and diagnostic printing.
25 Configuration precedence (highest first):
27 1. Explicit ``Control`` fields (``active_flavors``, ``trace_levels``)
28 2. Application-specific environment (``{APP}_ACTIVE_FLAVORS``,
29 ``{APP}_TRACE_LEVELS``)
30 3. Ictr environment (``ICTR_ACTIVE_FLAVORS``, ``ICTR_TRACE_LEVELS``)
31 4. Defaults (level-derived flavors; ictr built-in trace defaults)
32'''
33# TODO? Add structured logging support (JSON formatting for log aggregation)
34# TODO? Add distributed tracing support (correlation IDs, execution IDs)
35# TODO? Add metrics collection and reporting
36# TODO? Add OpenTelemetry integration
37# TODO: Add TOML configuration support for inscription control settings
40import logging as _logging
42from . import __
43from . import state as _state
46Levels: __.typx.TypeAlias = __.typx.Literal[
47 'debug', 'info', 'warn', 'error', 'critical' ]
49# Flavor base, active at every level: failures always print, and the
50# semantic flavors sit outside the level system (active means print).
51_ICTR_ERROR_FAMILY_FLAVORS = frozenset( {
52 'error', 'errorx', 'abort', 'abortx',
53} )
54_ICTR_SEMANTIC_FLAVORS = frozenset( {
55 'future', 'success', 'advice',
56} )
59class Presentations( __.enum.Enum ): # TODO: Python 3.11: StrEnum
60 ''' Scribe presentation modes. '''
62 Null = 'null' # deferred to external management
63 Plain = 'plain' # standard
64 Rich = 'rich' # enhanced with Rich
66Modes = Presentations # deprecated
69class TargetModes( __.enum.Enum ): # TODO: Python 3.11: StrEnum
70 ''' Target file mode control. '''
72 Append = 'append'
73 Truncate = 'truncate'
76class TargetDescriptor( __.immut.DataclassObject ):
77 ''' Descriptor for file-based inscription targets. '''
79 location: bytes | str | __.os.PathLike[ bytes ] | __.os.PathLike[ str ]
80 mode: TargetModes = TargetModes.Truncate
81 codec: str = 'utf-8'
84Target: __.typx.TypeAlias = __.typx.Union[
85 __.io.TextIOWrapper, __.typx.TextIO, TargetDescriptor ]
88class Control( __.immut.DataclassObject ):
89 ''' Application inscription configuration. '''
91 active_flavors: __.Absential[ __.ictr.ActiveFlavorsArgument ] = __.absent
92 ictr_alias: __.Absential[ str ] = __.absent
93 install_ictr: __.Absential[ bool ] = __.absent
94 level: Levels = 'info'
95 mode: Presentations = Presentations.Plain
96 target: Target = __.sys.stderr
97 trace_levels: __.Absential[ __.ictr.TraceLevelsArgument ] = __.absent
100def prepare( auxdata: _state.Globals, /, control: Control ) -> None:
101 ''' Prepares various scribes in a sensible manner. '''
102 target = _process_target( auxdata, control )
103 _prepare_scribes_logging( auxdata, control, target )
104 _prepare_scribes_ictr( auxdata, control, target )
107def _application_name_normalized( auxdata: _state.Globals ) -> str:
108 return ''.join(
109 c.upper( ) if c.isalnum( ) else '_'
110 for c in auxdata.application.name )
113def _derive_ictr_flavors( level_name: str ) -> frozenset[ str ]:
114 ''' Maps inscription level name to default active ictr flavors. '''
115 base = _ICTR_ERROR_FAMILY_FLAVORS | _ICTR_SEMANTIC_FLAVORS
116 match level_name.lower( ):
117 case 'debug':
118 return base | frozenset( { 'note', 'monition' } )
119 case 'info':
120 return base | frozenset( { 'note' } )
121 case 'warn' | 'warning':
122 return base | frozenset( { 'monition' } )
123 case _:
124 return base
127def _discover_inscription_level_name(
128 auxdata: _state.Globals, control: Control
129) -> str:
130 application_name = _application_name_normalized( auxdata )
131 for envvar_name_base in ( 'INSCRIPTION', 'LOG' ):
132 envvar_name = (
133 "{name}_{base}_LEVEL".format(
134 base = envvar_name_base, name = application_name ) )
135 if envvar_name in __.os.environ:
136 return __.os.environ[ envvar_name ]
137 return control.level
140def _prepare_logging_plain(
141 level: int, target: __.typx.TextIO, formatter: _logging.Formatter
142) -> None:
143 handler = _logging.StreamHandler( target )
144 handler.setFormatter( formatter )
145 _logging.basicConfig(
146 force = True, level = level, handlers = ( handler, ) )
149def _prepare_logging_rich(
150 level: int, target: __.typx.TextIO, formatter: _logging.Formatter
151) -> None:
152 try:
153 from rich.console import Console
154 from rich.logging import RichHandler
155 except ImportError:
156 # Gracefully degrade to plain mode.
157 _prepare_logging_plain( level, target, formatter )
158 return
159 console = Console( file = target )
160 handler = RichHandler(
161 console = console,
162 rich_tracebacks = True,
163 show_path = False, show_time = True )
164 handler.setFormatter( formatter )
165 _logging.basicConfig(
166 force = True, level = level, handlers = ( handler, ) )
169def _prepare_scribes_ictr(
170 auxdata: _state.Globals, control: Control, /, target: __.typx.TextIO
171) -> __.ictr.Dispatcher:
172 ''' Configures ictr dispatcher; installs into builtins when enabled. '''
173 active_flavors, evname_active_flavors = (
174 _resolve_ictr_active_flavors( auxdata, control ) )
175 trace_levels, evname_trace_levels = (
176 _resolve_ictr_trace_levels( auxdata, control ) )
177 printer_factories = _produce_ictr_generalcfg( control, target )
178 nomargs: dict[ str, __.typx.Any ] = dict(
179 active_flavors = active_flavors,
180 printer_factories = printer_factories,
181 trace_levels = trace_levels,
182 evname_active_flavors = evname_active_flavors,
183 evname_trace_levels = evname_trace_levels )
184 do_install = (
185 True if __.is_absent( control.install_ictr )
186 else control.install_ictr )
187 if do_install:
188 alias = (
189 __.ictr.builtins_alias_default
190 if __.is_absent( control.ictr_alias )
191 else control.ictr_alias )
192 return __.ictr.install( alias = alias, **nomargs )
193 return __.ictr.produce_dispatcher( **nomargs )
196def _prepare_scribes_logging(
197 auxdata: _state.Globals, control: Control, /, target: __.typx.TextIO
198) -> None:
199 level_name = _discover_inscription_level_name( auxdata, control )
200 level = getattr( _logging, level_name.upper( ) )
201 formatter = _logging.Formatter( "%(name)s: %(message)s" )
202 match control.mode:
203 case Presentations.Plain:
204 _prepare_logging_plain( level, target, formatter )
205 case Presentations.Rich:
206 _prepare_logging_rich( level, target, formatter )
207 case _: pass
210def _process_target(
211 auxdata: _state.Globals, control: Control
212) -> __.typx.TextIO:
213 target = control.target
214 if isinstance( target, __.typx.TextIO ): # pragma: no cover
215 return target
216 if isinstance( target, ( __.io.StringIO, __.io.TextIOWrapper ) ):
217 return target
218 location = target.location
219 if isinstance( location, __.os.PathLike ):
220 location = location.__fspath__( )
221 if isinstance( location, bytes ):
222 location = location.decode( )
223 location = __.Path( location )
224 location.parent.mkdir( exist_ok = True, parents = True )
225 mode = 'w' if target.mode is TargetModes.Truncate else 'a'
226 return auxdata.exits.enter_context( open(
227 location, mode = mode, encoding = target.codec ) )
230def _produce_ictr_generalcfg(
231 control: Control, target: __.typx.TextIO
232) -> __.ictr.PrinterFactoriesArgument:
233 ''' Produces ictr printer factories for the presentation mode.
235 Plain and Null modes never colorize, so ANSI sequences are always
236 stripped. Rich mode uses the default factory so TTY detection and
237 ``NO_COLOR`` remain with ictr.
238 '''
239 match control.mode:
240 case Presentations.Rich:
241 if isinstance( target, __.io.TextIOBase ): 241 ↛ 246line 241 didn't jump to line 246 because the condition on line 241 was always true
242 return (
243 __.ictr.produce_printer_factory_default( target ),
244 )
245 case _: pass
246 return (
247 __.ictr.produce_printer_factory_default(
248 target, colorize = False ),
249 )
252def _resolve_ictr_active_flavors(
253 auxdata: _state.Globals, control: Control
254) -> tuple[
255 __.ictr.ActiveFlavorsArgument,
256 __.ictr.EvnActiveFlavorsArgument,
257]:
258 ''' Resolves active flavors with Control > app env > ictr env > level. '''
259 if not __.is_absent( control.active_flavors ):
260 return control.active_flavors, None
261 app_evname = (
262 f"{_application_name_normalized( auxdata )}_ACTIVE_FLAVORS" )
263 if app_evname in __.os.environ:
264 return __.absent, app_evname
265 if 'ICTR_ACTIVE_FLAVORS' in __.os.environ:
266 return __.absent, __.absent
267 level_name = _discover_inscription_level_name( auxdata, control )
268 return _derive_ictr_flavors( level_name ), None
271def _resolve_ictr_trace_levels(
272 auxdata: _state.Globals, control: Control
273) -> tuple[
274 __.ictr.TraceLevelsArgument,
275 __.ictr.EvnTraceLevelsArgument,
276]:
277 ''' Resolves trace levels with Control > app env > ictr env > defaults. '''
278 if not __.is_absent( control.trace_levels ):
279 return control.trace_levels, None
280 app_evname = (
281 f"{_application_name_normalized( auxdata )}_TRACE_LEVELS" )
282 if app_evname in __.os.environ:
283 return __.absent, app_evname
284 return __.absent, __.absent