Skip to content

alog

Advanced logging utilities with custom levels, formatting, and async support.

This module provides: - Extended log levels (SPAM, VERBOSE, DEBUG0-3) - Custom formatter with compact headers - Easy setup via command-line arguments or programmatic config - Async-safe logging for signal handlers - Convenience functions for all log levels - Exception logging and raising helpers

The numeric values of the extended levels are: SPAM=8, VERBOSE=9, DEBUG0..3=11..14 (between DEBUG=10 and INFO=20).

Formatter

Bases: Formatter

Custom log formatter with compact headers and optional extra fields.

Header format: LEVELYYMMDD HH:MM:SS.mmmmmm;PID;MODULE[;EXTRA...]

Example
import io
import logging
import py_misc_utils.alog as alog

buf = io.StringIO()
logging.basicConfig(level=logging.INFO, stream=buf)
alog.set_current_level(logging.INFO, set_logger=False)

alog.info('hello %s', 'world')

# Header: 'IN' + timestamp;PID;module, then the message.
assert buf.getvalue().startswith('IN')
assert 'hello world' in buf.getvalue()
Source code in py_misc_utils/alog.py
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
class Formatter(logging.Formatter):
  """Custom log formatter with compact headers and optional extra fields.

  Header format: LEVELYYMMDD HH:MM:SS.mmmmmm;PID;MODULE[;EXTRA...]

  Example:
    import io
    import logging
    import py_misc_utils.alog as alog

    buf = io.StringIO()
    logging.basicConfig(level=logging.INFO, stream=buf)
    alog.set_current_level(logging.INFO, set_logger=False)

    alog.info('hello %s', 'world')

    # Header: 'IN' + timestamp;PID;module, then the message.
    assert buf.getvalue().startswith('IN')
    assert 'hello world' in buf.getvalue()
  """

  def __init__(self, emit_extra=None):
    """Initialize the formatter.

    Args:
      emit_extra: List of LogRecord attribute names to include in header
        (default: None).
    """
    super().__init__()
    self.emit_extra = emit_extra

  def format(self, r):
    """Format a log record.

    Args:
      r: LogRecord to format.

    Returns:
      Formatted log string with header and message.
    """
    hdr = self.make_header(r)
    msg = (r.msg % r.args) if r.args else r.msg

    return '\n'.join([f'{hdr}: {ln}' for ln in msg.split('\n')])

  def formatTime(self, r, datefmt=None):
    """Format the timestamp of a log record.

    Args:
      r: LogRecord.
      datefmt: Optional strftime format string.

    Returns:
      Formatted timestamp string with microsecond precision.
    """
    if datefmt:
      return time.strftime(datefmt, time.localtime(r.created))

    tstr = time.strftime('%Y%m%d %H:%M:%S', time.localtime(r.created))
    usecs = math.modf(r.created)[0] * 1e6

    return f'{tstr}.{usecs:06.0f}'

  def make_header(self, r):
    """Create the log header for a record.

    Args:
      r: LogRecord.

    Returns:
      Header string: LEVELYYMMDD HH:MM:SS.mmmmmm;PID;MODULE[;EXTRA...]
    """
    tstr = self.formatTime(r)
    lid = _SHORT_LEV.get(r.levelno, r.levelname[:2])
    hdr = f'{lid}{tstr};{os.getpid()};{r.module}'
    if self.emit_extra:
      extras = [str(getattr(r, name, None)) for name in self.emit_extra]
      hdr = f'{hdr};{";".join(extras)}'

    return hdr

format(r)

Format a log record.

Parameters:

Name Type Description Default
r

LogRecord to format.

required

Returns:

Type Description

Formatted log string with header and message.

Source code in py_misc_utils/alog.py
86
87
88
89
90
91
92
93
94
95
96
97
98
def format(self, r):
  """Format a log record.

  Args:
    r: LogRecord to format.

  Returns:
    Formatted log string with header and message.
  """
  hdr = self.make_header(r)
  msg = (r.msg % r.args) if r.args else r.msg

  return '\n'.join([f'{hdr}: {ln}' for ln in msg.split('\n')])

formatTime(r, datefmt=None)

Format the timestamp of a log record.

Parameters:

Name Type Description Default
r

LogRecord.

required
datefmt

Optional strftime format string.

None

Returns:

Type Description

Formatted timestamp string with microsecond precision.

Source code in py_misc_utils/alog.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def formatTime(self, r, datefmt=None):
  """Format the timestamp of a log record.

  Args:
    r: LogRecord.
    datefmt: Optional strftime format string.

  Returns:
    Formatted timestamp string with microsecond precision.
  """
  if datefmt:
    return time.strftime(datefmt, time.localtime(r.created))

  tstr = time.strftime('%Y%m%d %H:%M:%S', time.localtime(r.created))
  usecs = math.modf(r.created)[0] * 1e6

  return f'{tstr}.{usecs:06.0f}'

make_header(r)

Create the log header for a record.

Parameters:

Name Type Description Default
r

LogRecord.

required

Returns:

Type Description

Header string: LEVELYYMMDD HH:MM:SS.mmmmmm;PID;MODULE[;EXTRA...]

Source code in py_misc_utils/alog.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def make_header(self, r):
  """Create the log header for a record.

  Args:
    r: LogRecord.

  Returns:
    Header string: LEVELYYMMDD HH:MM:SS.mmmmmm;PID;MODULE[;EXTRA...]
  """
  tstr = self.formatTime(r)
  lid = _SHORT_LEV.get(r.levelno, r.levelname[:2])
  hdr = f'{lid}{tstr};{os.getpid()};{r.module}'
  if self.emit_extra:
    extras = [str(getattr(r, name, None)) for name in self.emit_extra]
    hdr = f'{hdr};{";".join(extras)}'

  return hdr

add_logging_options(parser)

Add logging-related command-line arguments to an ArgumentParser.

Parameters:

Name Type Description Default
parser

argparse.ArgumentParser instance to add arguments to.

required
Source code in py_misc_utils/alog.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
def add_logging_options(parser):
  """Add logging-related command-line arguments to an ArgumentParser.

  Args:
    parser: argparse.ArgumentParser instance to add arguments to.
  """
  parser.add_argument('--log_level',
                      type=str,
                      default=_DEFAULT_ARGS.get('log_level'),
                      choices={
                          'SPAM', 'VERBOSE', 'DEBUG', 'DEBUG0', 'DEBUG1', 'DEBUG2',
                          'DEBUG3', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'
                      },
                      help='The logging level')
  parser.add_argument('--log_file', type=str, default=_DEFAULT_ARGS.get('log_file'),
                      help='Comma separated list of target log files (STDOUT, STDERR ' \
                      'are also recognized)')
  parser.add_argument(
      '--log_mod_levels',
      nargs='*',
      help='Comma separated list of LOGGER_NAME,LEVEL to set the log level at')
  parser.add_argument('--log_emit_extra',
                      nargs='*',
                      help='Which other logging record fields should be emitted')

setup_logging(args)

Configure logging from parsed command-line arguments or namespace.

Parameters:

Name Type Description Default
args

Namespace or object with attributes: - log_level: Log level name (default: 'INFO') - log_file: Comma-separated list of files ('STDOUT', 'STDERR', or paths) - log_mod_levels: List of 'MODULE,LEVEL' strings - log_emit_extra: List of LogRecord fields to include in header

required
Source code in py_misc_utils/alog.py
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
def setup_logging(args):
  """Configure logging from parsed command-line arguments or namespace.

  Args:
    args: Namespace or object with attributes:
      - log_level: Log level name (default: 'INFO')
      - log_file: Comma-separated list of files ('STDOUT', 'STDERR', or paths)
      - log_mod_levels: List of 'MODULE,LEVEL' strings
      - log_emit_extra: List of LogRecord fields to include in header
  """
  _add_levels()
  _clear_logging_handlers()

  numeric_level = logging.getLevelName(args.log_level.upper())
  handlers = []
  if args.log_file:
    for fname in args.log_file.split(','):
      if fname == 'STDOUT':
        handler = logging.StreamHandler(sys.stdout)
      elif fname == 'STDERR':
        handler = logging.StreamHandler(sys.stderr)
      else:
        handler = logging.FileHandler(fname, mode='a')

      handler.setLevel(numeric_level)
      handler.setFormatter(Formatter(emit_extra=args.log_emit_extra))
      handlers.append(handler)

  logging.basicConfig(level=numeric_level, handlers=handlers, force=True)

  set_current_level(numeric_level, set_logger=False)

  _set_logmod_levels(args.log_mod_levels)

basic_setup(**kwargs)

Simple programmatic logging setup.

Parameters:

Name Type Description Default
**kwargs

Logging configuration options (log_level, log_file, etc.).

{}
Source code in py_misc_utils/alog.py
245
246
247
248
249
250
251
252
253
def basic_setup(**kwargs):
  """Simple programmatic logging setup.

  Args:
    **kwargs: Logging configuration options (log_level, log_file, etc.).
  """
  args = _DEFAULT_ARGS.copy()
  args.update(kwargs)
  setup_logging(types.SimpleNamespace(**args))

get_main_config()

Get a config object for use with py_misc_utils.config system.

Returns:

Type Description

SimpleNamespace with add_arguments and config_module attributes.

Source code in py_misc_utils/alog.py
256
257
258
259
260
261
262
263
def get_main_config():
  """Get a config object for use with py_misc_utils.config system.

  Returns:
    SimpleNamespace with add_arguments and config_module attributes.
  """
  return types.SimpleNamespace(add_arguments=add_logging_options,
                               config_module=setup_logging)

set_current_level(level, set_logger=True)

Set the current log level threshold.

Parameters:

Name Type Description Default
level

Numeric log level (e.g., logging.INFO).

required
set_logger

Whether to also update the root logger and handlers (default: True).

True
Source code in py_misc_utils/alog.py
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
def set_current_level(level, set_logger=True):
  """Set the current log level threshold.

  Args:
    level: Numeric log level (e.g., logging.INFO).
    set_logger: Whether to also update the root logger and handlers (default: True).
  """
  if set_logger:
    logger = logging.getLogger()
    logger.setLevel(level)
    for handler in logger.handlers:
      handler.setLevel(level)

  global _LEVEL

  _LEVEL = level

level_active(level)

Check if a log level is currently active (enabled).

Parameters:

Name Type Description Default
level

Numeric log level to check.

required

Returns:

Type Description

True if the level is at or above the current threshold - e.g. with

the threshold at INFO, level_active(INFO) is True while

level_active(DEBUG) is False.

Source code in py_misc_utils/alog.py
287
288
289
290
291
292
293
294
295
296
297
298
def level_active(level):
  """Check if a log level is currently active (enabled).

  Args:
    level: Numeric log level to check.

  Returns:
    True if the level is at or above the current threshold - e.g. with
    the threshold at INFO, level_active(INFO) is True while
    level_active(DEBUG) is False.
  """
  return _LEVEL <= level

level_run(level, fn)

Execute a function only if a log level is active.

Parameters:

Name Type Description Default
level

Numeric log level to check.

required
fn

Callable to execute if level is active.

required

Returns:

Type Description

Result of fn() if active, otherwise None.

Source code in py_misc_utils/alog.py
301
302
303
304
305
306
307
308
309
310
311
def level_run(level, fn):
  """Execute a function only if a log level is active.

  Args:
    level: Numeric log level to check.
    fn: Callable to execute if level is active.

  Returns:
    Result of fn() if active, otherwise None.
  """
  return fn() if level_active(level) else None

logging_args(kwargs)

Prepare logging keyword arguments with call limiting and stacklevel adjustment.

Parameters:

Name Type Description Default
kwargs

Keyword arguments for logging call.

required

Returns:

Type Description

Modified kwargs with adjusted stacklevel, or None if call limited.

Source code in py_misc_utils/alog.py
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
def logging_args(kwargs):
  """Prepare logging keyword arguments with call limiting and stacklevel adjustment.

  Args:
    kwargs: Keyword arguments for logging call.

  Returns:
    Modified kwargs with adjusted stacklevel, or None if call limited.
  """
  limit = kwargs.pop('limit', -1)
  stacklevel = kwargs.get('stacklevel', 1)
  if limit < 0 or cl.trigger(__file__, limit):
    kwargs['stacklevel'] = stacklevel + _LOGGING_FRAMES

    return kwargs

log(level, msg, *args, **kwargs)

Log a message at the specified level with call limiting.

Parameters:

Name Type Description Default
level

Numeric log level (e.g., logging.INFO).

required
msg

Message string or callable returning string.

required
*args

Format arguments for the message.

()
**kwargs

Additional logging arguments (limit, stacklevel, etc.).

{}
Source code in py_misc_utils/alog.py
360
361
362
363
364
365
366
367
368
369
370
371
def log(level, msg, *args, **kwargs):
  """Log a message at the specified level with call limiting.

  Args:
    level: Numeric log level (e.g., logging.INFO).
    msg: Message string or callable returning string.
    *args: Format arguments for the message.
    **kwargs: Additional logging arguments (limit, stacklevel, etc.).
  """
  kwargs = logging_args(kwargs)
  if kwargs is not None:
    logging.log(level, _dmsg(msg), *args, **kwargs)

spam(msg, *args, **kwargs)

Log a SPAM level message (very verbose).

Parameters:

Name Type Description Default
msg

Message string or callable.

required
*args

Format arguments.

()
**kwargs

Additional logging arguments.

{}
Source code in py_misc_utils/alog.py
374
375
376
377
378
379
380
381
382
383
def spam(msg, *args, **kwargs):
  """Log a SPAM level message (very verbose).

  Args:
    msg: Message string or callable.
    *args: Format arguments.
    **kwargs: Additional logging arguments.
  """
  if SPAM >= _LEVEL:
    log(SPAM, _dmsg(msg), *args, **_nested_args(kwargs))

verbose(msg, *args, **kwargs)

Log a VERBOSE level message.

Parameters:

Name Type Description Default
msg

Message string or callable.

required
*args

Format arguments.

()
**kwargs

Additional logging arguments.

{}
Source code in py_misc_utils/alog.py
386
387
388
389
390
391
392
393
394
395
def verbose(msg, *args, **kwargs):
  """Log a VERBOSE level message.

  Args:
    msg: Message string or callable.
    *args: Format arguments.
    **kwargs: Additional logging arguments.
  """
  if VERBOSE >= _LEVEL:
    log(VERBOSE, _dmsg(msg), *args, **_nested_args(kwargs))

debug0(msg, *args, **kwargs)

Log a DEBUG0 level message (least verbose debug).

Parameters:

Name Type Description Default
msg

Message string or callable.

required
*args

Format arguments.

()
**kwargs

Additional logging arguments.

{}
Source code in py_misc_utils/alog.py
398
399
400
401
402
403
404
405
406
407
def debug0(msg, *args, **kwargs):
  """Log a DEBUG0 level message (least verbose debug).

  Args:
    msg: Message string or callable.
    *args: Format arguments.
    **kwargs: Additional logging arguments.
  """
  if DEBUG0 >= _LEVEL:
    log(DEBUG0, _dmsg(msg), *args, **_nested_args(kwargs))

debug1(msg, *args, **kwargs)

Log a DEBUG1 level message.

Parameters:

Name Type Description Default
msg

Message string or callable.

required
*args

Format arguments.

()
**kwargs

Additional logging arguments.

{}
Source code in py_misc_utils/alog.py
410
411
412
413
414
415
416
417
418
419
def debug1(msg, *args, **kwargs):
  """Log a DEBUG1 level message.

  Args:
    msg: Message string or callable.
    *args: Format arguments.
    **kwargs: Additional logging arguments.
  """
  if DEBUG1 >= _LEVEL:
    log(DEBUG1, _dmsg(msg), *args, **_nested_args(kwargs))

debug2(msg, *args, **kwargs)

Log a DEBUG2 level message.

Parameters:

Name Type Description Default
msg

Message string or callable.

required
*args

Format arguments.

()
**kwargs

Additional logging arguments.

{}
Source code in py_misc_utils/alog.py
422
423
424
425
426
427
428
429
430
431
def debug2(msg, *args, **kwargs):
  """Log a DEBUG2 level message.

  Args:
    msg: Message string or callable.
    *args: Format arguments.
    **kwargs: Additional logging arguments.
  """
  if DEBUG2 >= _LEVEL:
    log(DEBUG2, _dmsg(msg), *args, **_nested_args(kwargs))

debug3(msg, *args, **kwargs)

Log a DEBUG3 level message (most verbose debug).

Parameters:

Name Type Description Default
msg

Message string or callable.

required
*args

Format arguments.

()
**kwargs

Additional logging arguments.

{}
Source code in py_misc_utils/alog.py
434
435
436
437
438
439
440
441
442
443
def debug3(msg, *args, **kwargs):
  """Log a DEBUG3 level message (most verbose debug).

  Args:
    msg: Message string or callable.
    *args: Format arguments.
    **kwargs: Additional logging arguments.
  """
  if DEBUG3 >= _LEVEL:
    log(DEBUG3, _dmsg(msg), *args, **_nested_args(kwargs))

debug(msg, *args, **kwargs)

Log a standard DEBUG level message.

Parameters:

Name Type Description Default
msg

Message string or callable.

required
*args

Format arguments.

()
**kwargs

Additional logging arguments.

{}
Source code in py_misc_utils/alog.py
446
447
448
449
450
451
452
453
454
455
def debug(msg, *args, **kwargs):
  """Log a standard DEBUG level message.

  Args:
    msg: Message string or callable.
    *args: Format arguments.
    **kwargs: Additional logging arguments.
  """
  if DEBUG >= _LEVEL:
    log(DEBUG, _dmsg(msg), *args, **_nested_args(kwargs))

info(msg, *args, **kwargs)

Log an INFO level message.

Parameters:

Name Type Description Default
msg

Message string or callable.

required
*args

Format arguments.

()
**kwargs

Additional logging arguments.

{}
Source code in py_misc_utils/alog.py
458
459
460
461
462
463
464
465
466
467
def info(msg, *args, **kwargs):
  """Log an INFO level message.

  Args:
    msg: Message string or callable.
    *args: Format arguments.
    **kwargs: Additional logging arguments.
  """
  if INFO >= _LEVEL:
    log(INFO, _dmsg(msg), *args, **_nested_args(kwargs))

warning(msg, *args, **kwargs)

Log a WARNING level message.

Parameters:

Name Type Description Default
msg

Message string or callable.

required
*args

Format arguments.

()
**kwargs

Additional logging arguments.

{}
Source code in py_misc_utils/alog.py
470
471
472
473
474
475
476
477
478
479
def warning(msg, *args, **kwargs):
  """Log a WARNING level message.

  Args:
    msg: Message string or callable.
    *args: Format arguments.
    **kwargs: Additional logging arguments.
  """
  if WARNING >= _LEVEL:
    log(WARNING, _dmsg(msg), *args, **_nested_args(kwargs))

error(msg, *args, **kwargs)

Log an ERROR level message.

Parameters:

Name Type Description Default
msg

Message string or callable.

required
*args

Format arguments.

()
**kwargs

Additional logging arguments.

{}
Source code in py_misc_utils/alog.py
482
483
484
485
486
487
488
489
490
491
def error(msg, *args, **kwargs):
  """Log an ERROR level message.

  Args:
    msg: Message string or callable.
    *args: Format arguments.
    **kwargs: Additional logging arguments.
  """
  if ERROR >= _LEVEL:
    log(ERROR, _dmsg(msg), *args, **_nested_args(kwargs))

critical(msg, *args, **kwargs)

Log a CRITICAL level message.

Parameters:

Name Type Description Default
msg

Message string or callable.

required
*args

Format arguments.

()
**kwargs

Additional logging arguments.

{}
Source code in py_misc_utils/alog.py
494
495
496
497
498
499
500
501
502
503
def critical(msg, *args, **kwargs):
  """Log a CRITICAL level message.

  Args:
    msg: Message string or callable.
    *args: Format arguments.
    **kwargs: Additional logging arguments.
  """
  if CRITICAL >= _LEVEL:
    log(CRITICAL, _dmsg(msg), *args, **_nested_args(kwargs))

exception(e, *args, **kwargs)

Log an exception with traceback at ERROR level.

Parameters:

Name Type Description Default
e

Exception instance.

required
*args

Format arguments.

()
**kwargs

Additional logging arguments. Supports 'exmsg' for custom prefix.

{}
Source code in py_misc_utils/alog.py
506
507
508
509
510
511
512
513
514
515
516
517
518
def exception(e, *args, **kwargs):
  """Log an exception with traceback at ERROR level.

  Args:
    e: Exception instance.
    *args: Format arguments.
    **kwargs: Additional logging arguments. Supports 'exmsg' for custom prefix.
  """
  kwargs = logging_args(kwargs)
  if kwargs is not None:
    msg = kwargs.pop('exmsg', 'Exception')
    tb = traceback.format_exc()
    error(f'{_dmsg(msg)}: {e}\n{tb}', *args, **_nested_args(kwargs))

xraise(e, msg, *args, **kwargs)

Raise an exception carrying a formatted message (and optionally log it).

The message is formatted as msg % args when format arguments are given - unlike the log functions, which use %-formatting at record rendering time.

Parameters:

Name Type Description Default
e

Exception class to raise (e.g., ValueError).

required
msg

Error message string or callable.

required
*args

Format arguments - applied with the % operator immediately.

()
**kwargs

Additional logging arguments. If 'logit' is True, the message is logged at ERROR level before raising.

{}

Raises:

Type Description
e

Instance of the provided exception class with the formatted message.

Source code in py_misc_utils/alog.py
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
def xraise(e, msg, *args, **kwargs):
  """Raise an exception carrying a formatted message (and optionally log it).

  The message is formatted as ``msg % args`` when format arguments are
  given - unlike the log functions, which use ``%``-formatting at record
  rendering time.

  Args:
    e: Exception class to raise (e.g., ValueError).
    msg: Error message string or callable.
    *args: Format arguments - applied with the % operator immediately.
    **kwargs: Additional logging arguments. If 'logit' is True, the
      message is logged at ERROR level before raising.

  Raises:
    e: Instance of the provided exception class with the formatted message.
  """
  if kwargs.pop('logit', False):
    error(msg, *args, **_nested_args(kwargs))

  raise e(_dmsg(msg) % args if args else _dmsg(msg))

async_log(level, msg, *args, **kwargs)

Log a message asynchronously (safe for signal handlers).

This function avoids the logging module's locks and can be safely called from signal handlers or other asynchronous contexts. It bypasses the configured handlers entirely, formatting the record with the default Formatter() and writing it to the output stream.

Parameters:

Name Type Description Default
level

Numeric log level.

required
msg

Message string or callable.

required
*args

Format arguments.

()
**kwargs

Additional arguments. 'file' specifies the output stream - stderr by default.

{}
Example
import io
import py_misc_utils.alog as alog

buf = io.StringIO()
alog.async_log(alog.INFO, 'async %s', 'msg', file=buf)

# Header: 'IN' + timestamp;PID;module, then the message.
assert buf.getvalue().startswith('IN')
assert 'async msg' in buf.getvalue()
Source code in py_misc_utils/alog.py
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
def async_log(level, msg, *args, **kwargs):
  """Log a message asynchronously (safe for signal handlers).

  This function avoids the logging module's locks and can be safely called
  from signal handlers or other asynchronous contexts. It bypasses the
  configured handlers entirely, formatting the record with the default
  Formatter() and writing it to the output stream.

  Args:
    level: Numeric log level.
    msg: Message string or callable.
    *args: Format arguments.
    **kwargs: Additional arguments. 'file' specifies the output stream -
      stderr by default.

  Example:
    import io
    import py_misc_utils.alog as alog

    buf = io.StringIO()
    alog.async_log(alog.INFO, 'async %s', 'msg', file=buf)

    # Header: 'IN' + timestamp;PID;module, then the message.
    assert buf.getvalue().startswith('IN')
    assert 'async msg' in buf.getvalue()
  """
  # This one cannot use the logging module as it could be called from signal
  # handler asycnhronously. The logging.getLevelName() is safe since it is simply
  # a (lockless) dictionary lookup.
  # Similarly, no other APIs taking locks can be called from this context.
  if level >= _LEVEL:
    kwargs = logging_args(kwargs)
    if kwargs is not None:
      # Fake a logging record, filling up only the fields used by the Formatter.
      # Do not call logging APIs for that, for the same reasons cited above.
      frame = tb.get_frame(n=1)
      module = frame.f_globals.get('__name__', 'ASYNC').split('.')[-1]

      now = time.time()
      record = types.SimpleNamespace(
          msg=_dmsg(msg),
          args=args,
          created=now,
          msecs=math.modf(now)[0] * 1000,
          levelno=level,
          levelname=logging.getLevelName(level),
          module=module,
      )

      formatter = Formatter()

      logfd = kwargs.pop('file', sys.stderr)
      logfd.write(formatter.format(record))
      logfd.write('\n')
      logfd.flush()