Skip to content

logging

Logging setup for AYON common package.

Three opt-in observability levels are supported, additive to each other: 1. Console (default) - human readable output to stderr. Always on. 2. NDJSON file - one JSON object per line, written to a local log file with retention. Enabled with 'AYON_LOG_TO_FILE=1'. 3. Vector - forward JSON logs to a Vector HTTP source. Enabled by setting 'AYON_VECTOR_LOG_URL'.

Console timestamps are in local time, formatted by 'AYON_LOG_CONSOLE_TIME_FORMAT' ('strftime' format, default '%Y/%m/%d %H:%M:%S'). JSON output always uses ISO 8601 in UTC.

Console layout is set by 'AYON_LOG_CONSOLE_STYLE': - 'ayon' (default) - log level without padding, e.g. '[info]', only the message is shown, logger name only with DEBUG log level. - 'structlog' - default structlog layout with padded log level, e.g. '[info ]', logger name and additional fields of records as 'key=value'.

Console message of spans contains their duration, e.g. 'launcher.bootstrap (duration 3.65s)', see 'log_span'.

Messages are message templates, e.g. 'log.info("Loaded {product}", product=name)', see 'render_message_template'.

VectorHTTPSender

Send rendered log records from a queue to a Vector HTTP source.

This is here so we can use Vector for log aggregation earlier before ayon-core and ayon-vector are started.

A daemon thread collects up to 'batch_size' records, or what arrived within 'flush_interval' seconds, and sends them as one JSON array per request. Vector's 'json' decoding creates one event per array item.

A circuit breaker stops sending for 'cooldown' seconds after 'failure_threshold' consecutive failed requests. Records are dropped meanwhile so a dead endpoint cannot slow down the process.

Failed requests are not repeated, except for a temporary error response of the endpoint. The next batch is the next attempt.

Source code in common/ayon_common/logging.py
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
class VectorHTTPSender:
    """Send rendered log records from a queue to a Vector HTTP source.

    This is here so we can use Vector for log aggregation
    earlier before ayon-core and ayon-vector are started.

    A daemon thread collects up to 'batch_size' records, or what arrived
    within 'flush_interval' seconds, and sends them as one JSON array per
    request. Vector's 'json' decoding creates one event per array item.

    A circuit breaker stops sending for 'cooldown' seconds after
    'failure_threshold' consecutive failed requests. Records are dropped
    meanwhile so a dead endpoint cannot slow down the process.

    Failed requests are not repeated, except for a temporary error
    response of the endpoint. The next batch is the next attempt.
    """

    _stop_sentinel = object()

    def __init__(
        self,
        url: str,
        log_queue: queue.Queue[str | None],
        batch_size: int = VECTOR_BATCH_SIZE,
        flush_interval: float = VECTOR_FLUSH_INTERVAL,
        failure_threshold: int = VECTOR_FAILURE_THRESHOLD,
        cooldown: float = VECTOR_CIRCUIT_COOLDOWN,
    ):
        self._url = url
        self._queue = log_queue
        self._batch_size = batch_size
        self._flush_interval = flush_interval
        self._failure_threshold = failure_threshold
        self._cooldown = cooldown
        self._consecutive_failures = 0
        self._circuit_open_until = 0.0
        self._thread: threading.Thread | None = None
        # 'stop' was called, see '_send'
        self._stopping = False
        self._gave_up = False
        # Reuse a single session so repeated POSTs reuse pooled
        # connections instead of opening a new one per request.
        self._session = requests.Session()
        # Only temporary error responses are retried. Connection and read
        #   errors are not: an unreachable endpoint rarely recovers within
        #   the backoff, each attempt waits for the timeout again, and
        #   a batch whose response was not read would be sent twice.
        retry = urllib3.util.Retry(
            total=2,
            connect=0,
            read=0,
            backoff_factor=0.3,
            status_forcelist=(502, 503, 504),
            allowed_methods=("POST",),
        )
        adapter = requests.adapters.HTTPAdapter(
            pool_connections=1, pool_maxsize=1, max_retries=retry
        )
        self._session.mount("http://", adapter)
        self._session.mount("https://", adapter)

    def start(self) -> None:
        self._stopping = False
        self._gave_up = False
        self._thread = threading.Thread(
            target=self._run, name="AYONVectorSender", daemon=True
        )
        self._thread.start()

    def stop(self, timeout: float = 5.0) -> None:
        """Send records remaining in the queue and stop the thread.

        Called on exit of the process. Remaining records are dropped
        after the first failed request, an unreachable endpoint must
        not delay the exit by an attempt for each remaining batch.
        """
        if self._thread is None:
            return
        self._stopping = True
        # Thread may already be finished, see 'request_stop'
        if self._thread.is_alive():
            try:
                self._queue.put(None, timeout=timeout)
            except queue.Full:
                pass
            self._thread.join(timeout)
        self._thread = None
        self._session.close()

    def request_stop(self) -> None:
        """Stop the thread once records in the queue are sent.

        Does not wait for the thread. 'stop' registered at exit still
        waits for records which were not sent yet.
        """
        if self._thread is None:
            return
        try:
            self._queue.put_nowait(None)
        except queue.Full:
            # Thread runs until exit, 'stop' handles it
            pass

    def _run(self) -> None:
        stop = False
        while not stop:
            item = self._queue.get()
            if item is None:
                break
            batch = [item]
            deadline = time.monotonic() + self._flush_interval
            while len(batch) < self._batch_size:
                remaining = deadline - time.monotonic()
                if remaining <= 0:
                    break
                try:
                    item = self._queue.get(timeout=remaining)
                except queue.Empty:
                    break
                if item is None:
                    stop = True
                    break
                batch.append(item)
            self._send(batch)

    def _send(self, batch: list[str]) -> None:
        now = time.monotonic()
        if now < self._circuit_open_until:
            # Circuit is open - skip the HTTP attempt entirely so a dead
            # Vector endpoint cannot slow down the sender thread.
            return
        if self._gave_up:
            return
        try:
            response = self._session.post(
                self._url,
                data="[{}]".format(",".join(batch)).encode("utf-8"),
                headers={"Content-Type": "application/json"},
                # (connect timeout, read timeout) - a slow-but-alive
                # endpoint should not stall as long as a dead one.
                timeout=(0.3, 2.0),
            )
            response.raise_for_status()
        except Exception:  # noqa: BLE001
            if self._stopping:
                # Process is exiting, see 'stop'
                self._gave_up = True
            self._consecutive_failures += 1
            if self._consecutive_failures >= self._failure_threshold:
                self._circuit_open_until = now + self._cooldown
                self._consecutive_failures = 0
                _vector_warn_logger.warning(
                    "Vector endpoint unreachable, pausing log delivery"
                    " for %s seconds.",
                    self._cooldown,
                )
            else:
                # Rate-limit warnings in case of Vector outage.
                _vector_warn_logger.warning(
                    "Failed to send %s log records to Vector.", len(batch)
                )
        else:
            self._consecutive_failures = 0

request_stop()

Stop the thread once records in the queue are sent.

Does not wait for the thread. 'stop' registered at exit still waits for records which were not sent yet.

Source code in common/ayon_common/logging.py
777
778
779
780
781
782
783
784
785
786
787
788
789
def request_stop(self) -> None:
    """Stop the thread once records in the queue are sent.

    Does not wait for the thread. 'stop' registered at exit still
    waits for records which were not sent yet.
    """
    if self._thread is None:
        return
    try:
        self._queue.put_nowait(None)
    except queue.Full:
        # Thread runs until exit, 'stop' handles it
        pass

stop(timeout=5.0)

Send records remaining in the queue and stop the thread.

Called on exit of the process. Remaining records are dropped after the first failed request, an unreachable endpoint must not delay the exit by an attempt for each remaining batch.

Source code in common/ayon_common/logging.py
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
def stop(self, timeout: float = 5.0) -> None:
    """Send records remaining in the queue and stop the thread.

    Called on exit of the process. Remaining records are dropped
    after the first failed request, an unreachable endpoint must
    not delay the exit by an attempt for each remaining batch.
    """
    if self._thread is None:
        return
    self._stopping = True
    # Thread may already be finished, see 'request_stop'
    if self._thread.is_alive():
        try:
            self._queue.put(None, timeout=timeout)
        except queue.Full:
            pass
        self._thread.join(timeout)
    self._thread = None
    self._session.close()

log_span

Measure a block of code and log it as one structured span record.

Launcher counterpart of 'ayon_core.lib.log_span' producing the same fields, so spans of the launcher are queried as those of 'ayon_core'. 'ayon_core' is not available during launcher startup, and it can't use this class because older launchers don't have it.

Record is logged when the span ends, with the span name as the event and fields 'duration_ms', 'status' ('ok' or 'error'), 'trace_id', 'span_id', 'parent_span_id' and passed attributes. 'SystemExit' with a non-zero code is an error, the code is stored as 'exit_code'. Console message also contains the duration, e.g. 'launcher.bootstrap (duration 3.65s)'.

While the span is open, 'trace_id' and 'span_id' are bound to structlog context variables, so all records logged meanwhile carry them. Nested spans share 'trace_id' of the outermost span.

Span can end before its block with 'finish', e.g. before logging is released. Spans nested in it which are still open are finished first, as successful. Ending a span again has no effect, so their blocks may end later.

Parameters:

Name Type Description Default
name str

Span name used as the log event. Should be stable and low-cardinality (e.g. 'launcher.distribute').

required
level int

Log level of the span record.

INFO
start Optional[float]

'time.perf_counter()' value when the span started. Time of entering the span is used by default.

None
**attributes Any

Additional fields of the span record.

{}
Example

with log_span("launcher.distribute") as span: distribution.distribute() span.set(need_installer_change=True)

Source code in common/ayon_common/logging.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
class log_span:  # noqa: N801
    """Measure a block of code and log it as one structured span record.

    Launcher counterpart of 'ayon_core.lib.log_span' producing the same
    fields, so spans of the launcher are queried as those of 'ayon_core'.
    'ayon_core' is not available during launcher startup, and it can't
    use this class because older launchers don't have it.

    Record is logged when the span ends, with the span name as the event
    and fields 'duration_ms', 'status' ('ok' or 'error'), 'trace_id',
    'span_id', 'parent_span_id' and passed attributes. 'SystemExit' with
    a non-zero code is an error, the code is stored as 'exit_code'.
    Console message also contains the duration, e.g.
    'launcher.bootstrap (duration 3.65s)'.

    While the span is open, 'trace_id' and 'span_id' are bound to
    structlog context variables, so all records logged meanwhile carry
    them. Nested spans share 'trace_id' of the outermost span.

    Span can end before its block with 'finish', e.g. before logging is
    released. Spans nested in it which are still open are finished first,
    as successful. Ending a span again has no effect, so their blocks may
    end later.

    Args:
        name (str): Span name used as the log event. Should be stable and
            low-cardinality (e.g. 'launcher.distribute').
        level (int): Log level of the span record.
        start (Optional[float]): 'time.perf_counter()' value when the span
            started. Time of entering the span is used by default.
        **attributes (Any): Additional fields of the span record.

    Example:
        with log_span("launcher.distribute") as span:
            distribution.distribute()
            span.set(need_installer_change=True)

    """

    def __init__(
        self,
        name: str,
        *,
        level: int = logging.INFO,
        start: float | None = None,
        **attributes: Any,
    ) -> None:
        self._name = name
        self._level = level
        self._start = start
        self._attributes = attributes
        self._trace_id = ""
        self._span_id = ""
        self._parent: log_span | None = None
        self._span_token: contextvars.Token | None = None
        self._contextvars_tokens: dict[str, contextvars.Token] = {}
        self._finished = False

    @property
    def trace_id(self) -> str:
        return self._trace_id

    @property
    def span_id(self) -> str:
        return self._span_id

    def set(self, **attributes: Any) -> None:
        """Add attributes known only after the span started.

        Args:
            **attributes (Any): Additional fields of the span record.

        """
        self._attributes.update(attributes)

    def __enter__(self) -> "log_span":
        self._parent = _current_span.get()
        if self._parent is None:
            self._trace_id = secrets.token_hex(16)
        else:
            self._trace_id = self._parent.trace_id
        self._span_id = secrets.token_hex(8)
        self._span_token = _current_span.set(self)
        self._contextvars_tokens = structlog.contextvars.bind_contextvars(
            trace_id=self._trace_id,
            span_id=self._span_id,
        )
        if self._start is None:
            self._start = time.perf_counter()
        return self

    def __exit__(self, exc_type, exc_value, exc_tb) -> None:
        self.finish(exc_type, exc_value)

    def finish(
        self,
        exc_type: type[BaseException] | None = None,
        exc_value: BaseException | None = None,
    ) -> None:
        """End the span and log its record.

        Args:
            exc_type (Optional[type[BaseException]]): Type of exception
                which ended the span.
            exc_value (Optional[BaseException]): Exception which ended
                the span.

        """
        if self._finished or self._span_token is None:
            return

        # Finish nested spans still open, innermost first, so context
        #   variables are restored in order
        nested = []
        span = _current_span.get()
        while span is not None and span is not self:
            nested.append(span)
            span = span._parent
        if span is self:
            for span in nested:
                span.finish()

        self._finished = True
        duration = time.perf_counter() - (self._start or 0.0)
        structlog.contextvars.reset_contextvars(**self._contextvars_tokens)
        _current_span.reset(self._span_token)

        if not logging.getLogger(SPAN_LOGGER_NAME).isEnabledFor(self._level):
            return

        fields: dict[str, Any] = {
            "trace_id": self._trace_id,
            "span_id": self._span_id,
            "duration_ms": round(duration * 1000, 3),
        }
        fields.update(self._attributes)
        status = "ok"
        if isinstance(exc_value, SystemExit):
            code = exc_value.code
            # Same exit code as the interpreter uses, 'None' is success
            #   and other non-int values (e.g. message) are failure
            exit_code = (
                code if isinstance(code, int) else int(code is not None)
            )
            fields["exit_code"] = exit_code
            if exit_code != 0:
                status = "error"
        elif exc_type is not None:
            status = "error"
            fields["error_type"] = exc_type.__name__
        fields["status"] = status
        if self._parent is not None:
            fields["parent_span_id"] = self._parent.span_id

        structlog.get_logger(SPAN_LOGGER_NAME).log(
            self._level, self._name, **fields
        )

finish(exc_type=None, exc_value=None)

End the span and log its record.

Parameters:

Name Type Description Default
exc_type Optional[type[BaseException]]

Type of exception which ended the span.

None
exc_value Optional[BaseException]

Exception which ended the span.

None
Source code in common/ayon_common/logging.py
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
def finish(
    self,
    exc_type: type[BaseException] | None = None,
    exc_value: BaseException | None = None,
) -> None:
    """End the span and log its record.

    Args:
        exc_type (Optional[type[BaseException]]): Type of exception
            which ended the span.
        exc_value (Optional[BaseException]): Exception which ended
            the span.

    """
    if self._finished or self._span_token is None:
        return

    # Finish nested spans still open, innermost first, so context
    #   variables are restored in order
    nested = []
    span = _current_span.get()
    while span is not None and span is not self:
        nested.append(span)
        span = span._parent
    if span is self:
        for span in nested:
            span.finish()

    self._finished = True
    duration = time.perf_counter() - (self._start or 0.0)
    structlog.contextvars.reset_contextvars(**self._contextvars_tokens)
    _current_span.reset(self._span_token)

    if not logging.getLogger(SPAN_LOGGER_NAME).isEnabledFor(self._level):
        return

    fields: dict[str, Any] = {
        "trace_id": self._trace_id,
        "span_id": self._span_id,
        "duration_ms": round(duration * 1000, 3),
    }
    fields.update(self._attributes)
    status = "ok"
    if isinstance(exc_value, SystemExit):
        code = exc_value.code
        # Same exit code as the interpreter uses, 'None' is success
        #   and other non-int values (e.g. message) are failure
        exit_code = (
            code if isinstance(code, int) else int(code is not None)
        )
        fields["exit_code"] = exit_code
        if exit_code != 0:
            status = "error"
    elif exc_type is not None:
        status = "error"
        fields["error_type"] = exc_type.__name__
    fields["status"] = status
    if self._parent is not None:
        fields["parent_span_id"] = self._parent.span_id

    structlog.get_logger(SPAN_LOGGER_NAME).log(
        self._level, self._name, **fields
    )

set(**attributes)

Add attributes known only after the span started.

Parameters:

Name Type Description Default
**attributes Any

Additional fields of the span record.

{}
Source code in common/ayon_common/logging.py
259
260
261
262
263
264
265
266
def set(self, **attributes: Any) -> None:
    """Add attributes known only after the span started.

    Args:
        **attributes (Any): Additional fields of the span record.

    """
    self._attributes.update(attributes)

configure_logging()

Set up logging for AYON common package.

Sets up structlog with a console renderer and a JSON renderer for sending logs to Vector.

Safe to call multiple times, and safe even if another package (e.g. 'ayon_core') configures logging first - only the first call in the process has any effect, to avoid attaching duplicate handlers.

Source code in common/ayon_common/logging.py
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
def configure_logging() -> None:
    """Set up logging for AYON common package.

    Sets up structlog with a console renderer
    and a JSON renderer for sending logs to Vector.

    Safe to call multiple times, and safe even if another package (e.g.
    'ayon_core') configures logging first - only the first call in the
    process has any effect, to avoid attaching duplicate handlers.

    """
    global _logging_state

    # 'structlog.is_configured()' is process-wide, so it also guards
    # against other packages (e.g. 'ayon_core') configuring logging first.
    if structlog.is_configured():
        return
    # Configure structlog
    def _add_site_id(logger, method_name, event_dict):
        event_dict.setdefault(
            "site_id", os.environ.get("AYON_SITE_ID", "unknown")
        )
        return event_dict

    def _add_session_id(logger, method_name, event_dict):
        # Read on each record, context variables bound in the main thread
        #   would not be available in other threads.
        session_id = os.environ.get("AYON_SESSION_ID")
        if session_id:
            event_dict.setdefault("session_id", session_id)
        return event_dict

    def _drop_log_context(logger, method_name, event_dict):
        # Keep context fields in JSON sent to Vector but not in console
        # output - full ids make console output hard to read. Trace and
        # span ids are added by 'ayon_core.lib.log_span'.
        for key in (
            "site_id",
            "session_id",
            "trace_id",
            "span_id",
            "parent_span_id",
            MESSAGE_TEMPLATE_KEY,
        ):
            event_dict.pop(key, None)
        return event_dict

    positional_args_formatter = (
        structlog.stdlib.PositionalArgumentsFormatter()
    )

    def _format_positional_args(logger, method_name, event_dict):
        # Arguments not matching the message must not raise in the
        #   code that logs, e.g. 'log.info("Data:", data)'. Standard
        #   library logger reports them to stderr and drops the
        #   record, here they are added to the message instead.
        try:
            return positional_args_formatter(
                logger, method_name, event_dict
            )
        except Exception:  # noqa: BLE001
            args = event_dict.pop("positional_args", ())
            try:
                formatted_args = " ".join(repr(arg) for arg in args)
            except Exception:  # noqa: BLE001
                formatted_args = "<unprintable arguments>"
            event_dict["event"] = (
                f"{event_dict.get('event')} {formatted_args}"
            )
            return event_dict

    def _format_message(logger, method_name, event_dict):
        # Message template, or '%s' style arguments
        event_dict = _render_message(logger, method_name, event_dict)
        return _format_positional_args(logger, method_name, event_dict)

    shared_processors: list[Callable] = [
        structlog.contextvars.merge_contextvars,
        structlog.processors.add_log_level,
        structlog.stdlib.add_logger_name,
        structlog.processors.TimeStamper(fmt="iso"),
        structlog.processors.StackInfoRenderer(),
        _add_site_id,
        _add_session_id,
    ]

    structlog.configure(
        processors=shared_processors + [
            # Support message templates, e.g.
            #   'log.info("Loaded {name}", name=name)', and '%s' style
            #   arguments, e.g. 'log.info("Loaded %s", name)'. Records
            #   from plain stdlib loggers are already formatted by
            #   'ProcessorFormatter' via 'record.getMessage()'.
            _format_message,
            # Hand over to standard logging, rendered by formatters
            _render_for_stdlib,
        ],
        logger_factory=structlog.stdlib.LoggerFactory(),
        wrapper_class=_LevelAwareBoundLogger,
        cache_logger_on_first_use=True,
    )

    console_timestamper = _create_console_timestamper(
        get_console_time_format_from_env()
    )
    ayon_console_style = get_console_style_from_env() == CONSOLE_STYLE_AYON
    # AYON layout shows only the message, fields are in log file and
    #   Vector. Logger name is shown only for debugging.
    show_key_values = not ayon_console_style
    show_logger_name = (
        not ayon_console_style
        or get_log_level_from_env() <= logging.DEBUG
    )
    console_processors: list[Callable] = [
        console_timestamper,
        structlog.stdlib.ProcessorFormatter.remove_processors_meta,
        _drop_log_context,
        _add_span_duration_to_event,
    ]

    def _create_console_formatter(colors: bool) -> logging.Formatter:
        return _EventDictProcessorFormatter(
            foreign_pre_chain=shared_processors,
            processors=[
                *console_processors,
                _ConsoleRenderer(
                    colors=colors,
                    exception_formatter=(
                        _get_console_exception_formatter(colors)
                    ),
                    compact_level=ayon_console_style,
                    show_key_values=show_key_values,
                    show_logger_name=show_logger_name,
                ),
            ],
        )

    json_formatter = _EventDictProcessorFormatter(
        foreign_pre_chain=shared_processors,
        processors=[
            structlog.stdlib.ProcessorFormatter.remove_processors_meta,
            structlog.processors.format_exc_info,
            structlog.processors.JSONRenderer(),
        ],
    )

    handler = _StderrHandler(
        color_formatter=_create_console_formatter(colors=True)
    )
    handler.setFormatter(_create_console_formatter(colors=False))

    # Failed setup of log file or Vector must not break the process,
    #   console output is kept. Warnings are logged once handlers are
    #   added.
    setup_warnings: list[tuple[str, Exception]] = []
    file_handler: TimedRotatingFileHandler | None = None
    if LOG_FILE_ENABLED:
        try:
            log_dir = get_launcher_local_dir("logs", create=True)
            _remove_old_log_files(log_dir, LOG_FILE_RETENTION_DAYS)
            file_handler = TimedRotatingFileHandler(
                _get_log_file_path(log_dir),
                when="midnight",
                backupCount=LOG_FILE_RETENTION_DAYS,
                encoding="utf-8",
            )
        except Exception as exc:  # noqa: BLE001
            # E.g. the directory is not writable or the disk is full
            setup_warnings.append((
                "Failed to create AYON log file, logging to file"
                " is disabled: %s",
                exc,
            ))
        else:
            file_handler.setFormatter(json_formatter)

    queue_handler: _DroppingQueueHandler | None = None
    vector_sender: VectorHTTPSender | None = None
    if VECTOR_LOG_URL:
        # Send logs to Vector asynchronously so HTTP calls
        # don't block the app.
        # Queue is bounded so a Vector outage drops records instead of
        # growing memory without bound.
        log_queue: queue.Queue = queue.Queue(VECTOR_QUEUE_MAX_SIZE)
        try:
            vector_sender = VectorHTTPSender(VECTOR_LOG_URL, log_queue)
            vector_sender.start()
        except Exception as exc:  # noqa: BLE001
            vector_sender = None
            setup_warnings.append((
                "Failed to start sending of logs to Vector, it"
                " is disabled: %s",
                exc,
            ))
        else:
            queue_handler = _DroppingQueueHandler(log_queue)
            queue_handler.setFormatter(json_formatter)
            # The sender thread is a daemon thread, it would be killed
            # on interpreter exit with records still in the queue.
            # Stopping it at exit delivers the queued records first.
            atexit.register(vector_sender.stop)

    log_level = get_log_level_from_env()
    root_logger = logging.getLogger()
    state = _LoggingState(root_level=root_logger.level)
    # Set level first, root logger default WARNING would drop INFO below
    root_logger.setLevel(log_level)
    root_logger.addHandler(handler)
    state.handlers.append(handler)
    if file_handler is not None:
        root_logger.addHandler(file_handler)
        state.handlers.append(file_handler)
    if queue_handler is not None:
        root_logger.info(
            "Vector logging enabled",
            extra={"vector_log_url": VECTOR_LOG_URL},
        )
        root_logger.addHandler(queue_handler)
        state.handlers.append(queue_handler)
        state.vector_sender = vector_sender
    for message, exc in setup_warnings:
        logging.getLogger(__name__).warning(message, exc)

    if log_level < logging.INFO:
        # force silence for some very noisy loggers
        for name in ("urllib3", "requests", "GlobalServerAPI"):
            logger = logging.getLogger(name)
            state.logger_levels[name] = logger.level
            logger.setLevel(logging.WARNING)

    _logging_state = state

get_console_style_from_env()

Resolve console layout from environment variables.

'AYON_LOG_CONSOLE_STYLE' accepts: - 'ayon' (default) - log level without padding, e.g. '[info]', 'key=value' fields of records never shown and logger name shown only with DEBUG log level. - 'structlog' - default structlog layout, padded log level, logger name and 'key=value' fields always shown.

Invalid value is handled as 'ayon'.

Returns:

Name Type Description
str str

'CONSOLE_STYLE_AYON' or 'CONSOLE_STYLE_STRUCTLOG'.

Source code in common/ayon_common/logging.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def get_console_style_from_env() -> str:
    """Resolve console layout from environment variables.

    'AYON_LOG_CONSOLE_STYLE' accepts:
        - 'ayon' (default) - log level without padding, e.g. '[info]',
            'key=value' fields of records never shown and logger name
            shown only with DEBUG log level.
        - 'structlog' - default structlog layout, padded log level,
            logger name and 'key=value' fields always shown.

    Invalid value is handled as 'ayon'.

    Returns:
        str: 'CONSOLE_STYLE_AYON' or 'CONSOLE_STYLE_STRUCTLOG'.

    """
    style = os.getenv("AYON_LOG_CONSOLE_STYLE", "").strip().lower()
    if style == CONSOLE_STYLE_STRUCTLOG:
        return CONSOLE_STYLE_STRUCTLOG
    return CONSOLE_STYLE_AYON

get_console_time_format_from_env()

Resolve format of console timestamps from environment variables.

'AYON_LOG_CONSOLE_TIME_FORMAT' accepts a 'strftime' format, e.g. '%H:%M:%S.%f'. Defaults to 'DEFAULT_CONSOLE_TIME_FORMAT' when it is not set or is invalid.

Returns:

Name Type Description
str str

Format of console timestamps.

Source code in common/ayon_common/logging.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
def get_console_time_format_from_env() -> str:
    """Resolve format of console timestamps from environment variables.

    'AYON_LOG_CONSOLE_TIME_FORMAT' accepts a 'strftime' format, e.g.
    '%H:%M:%S.%f'. Defaults to 'DEFAULT_CONSOLE_TIME_FORMAT' when it is
    not set or is invalid.

    Returns:
        str: Format of console timestamps.

    """
    time_format = os.getenv("AYON_LOG_CONSOLE_TIME_FORMAT", "")
    if not time_format:
        return DEFAULT_CONSOLE_TIME_FORMAT
    try:
        # Invalid directives raise 'ValueError' on some platforms
        datetime.datetime.now().strftime(time_format)
    except ValueError:
        return DEFAULT_CONSOLE_TIME_FORMAT
    return time_format

get_log_level_from_env()

Resolve the AYON log level from environment variables.

'AYON_LOG_LEVEL' accepts a numeric ('10') or a named ('DEBUG') level. Defaults to INFO when it is not set or is invalid.

Returns:

Name Type Description
int int

Log level.

Source code in common/ayon_common/logging.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def get_log_level_from_env() -> int:
    """Resolve the AYON log level from environment variables.

    'AYON_LOG_LEVEL' accepts a numeric ('10') or a named ('DEBUG') level.
    Defaults to INFO when it is not set or is invalid.

    Returns:
        int: Log level.

    """
    log_level = os.getenv("AYON_LOG_LEVEL", "").strip()
    if log_level:
        if log_level.isdigit():
            level = int(log_level)
        else:
            level = logging.getLevelNamesMapping().get(log_level.upper(), 0)
        if level > 0:
            return level
    return logging.INFO

release_logging()

Undo 'configure_logging' before control is passed to 'ayon_core'.

Logging of the launcher process belongs to 'ayon_core' once it is started, it configures logging for its own needs. Handlers added by 'configure_logging' are removed, levels of the root logger and of silenced loggers are restored and structlog configuration is reset.

Records already queued for Vector are sent in the background, the sender thread stops afterwards. Does nothing if 'configure_logging' did not configure logging.

Source code in common/ayon_common/logging.py
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
def release_logging() -> None:
    """Undo 'configure_logging' before control is passed to 'ayon_core'.

    Logging of the launcher process belongs to 'ayon_core' once it is
    started, it configures logging for its own needs. Handlers added by
    'configure_logging' are removed, levels of the root logger and of
    silenced loggers are restored and structlog configuration is reset.

    Records already queued for Vector are sent in the background, the
    sender thread stops afterwards. Does nothing if 'configure_logging'
    did not configure logging.
    """
    global _logging_state

    state = _logging_state
    if state is None:
        return
    _logging_state = None

    root_logger = logging.getLogger()
    for handler in state.handlers:
        root_logger.removeHandler(handler)
        handler.close()
    root_logger.setLevel(state.root_level)
    for name, level in state.logger_levels.items():
        logging.getLogger(name).setLevel(level)

    if state.vector_sender is not None:
        state.vector_sender.request_stop()

    structlog.reset_defaults()
    structlog.contextvars.clear_contextvars()

render_message_template(template, fields)

Render a message template with values of fields.

Template uses Python format string syntax with named fields, e.g. 'Published {product} v{version:03d}'. Conversions ('{name!r}') and format specs ('{name:>10}') are supported, '{{' and '}}' are literal braces.

Unlike 'str.format', rendering never raises and each field is handled on its own: - Field without a value is kept as written, e.g. '{missing:03d}'. - Positional ('{}', '{0}'), attribute ('{obj.name}') and index ('{data[key]}') fields are kept as written, values are only looked up by name. - Value not matching its format spec is rendered by 'str'. - Message which is not a valid format string, e.g. 'Unclosed {', is returned unchanged.

Parameters:

Name Type Description Default
template str

Message template, e.g. 'Loaded {product}'.

required
fields Mapping[str, Any]

Values of fields.

required

Returns:

Name Type Description
str str

Rendered message.

Source code in common/ayon_common/logging.py
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
def render_message_template(
    template: str, fields: Mapping[str, Any]
) -> str:
    """Render a message template with values of fields.

    Template uses Python format string syntax with named fields, e.g.
    'Published {product} v{version:03d}'. Conversions ('{name!r}') and
    format specs ('{name:>10}') are supported, '{{' and '}}' are literal
    braces.

    Unlike 'str.format', rendering never raises and each field is handled
    on its own:
        - Field without a value is kept as written, e.g. '{missing:03d}'.
        - Positional ('{}', '{0}'), attribute ('{obj.name}') and index
            ('{data[key]}') fields are kept as written, values are only
            looked up by name.
        - Value not matching its format spec is rendered by 'str'.
        - Message which is not a valid format string, e.g. 'Unclosed {',
            is returned unchanged.

    Args:
        template (str): Message template, e.g. 'Loaded {product}'.
        fields (Mapping[str, Any]): Values of fields.

    Returns:
        str: Rendered message.

    """
    parsed = _get_message_template(template)
    if parsed is None:
        return template

    parts = []
    for literal, field_name, format_spec, conversion in parsed:
        parts.append(literal)
        if field_name is None:
            continue
        if field_name not in fields:
            conversion = f"!{conversion}" if conversion else ""
            format_spec = f":{format_spec}" if format_spec else ""
            parts.append(f"{{{field_name}{conversion}{format_spec}}}")
            continue
        value = fields[field_name]
        try:
            if conversion == "r":
                value = repr(value)
            elif conversion == "s":
                value = str(value)
            elif conversion == "a":
                value = ascii(value)
            parts.append(format(value, format_spec or ""))
        except Exception:  # noqa: BLE001
            try:
                parts.append(str(value))
            except Exception:  # noqa: BLE001
                parts.append("{" + field_name + "}")
    return "".join(parts)