unaiverse.utils.logger¶
The node, the agent, the world and the code of the roles all log through one object, log. Each record goes to one channel. A channel is a category of output (network events, sessions, the messages for the user, ...) and not a level of severity. The logger decides for each channel independently whether it records it and whether it prints it on screen. A record is a JSON object. The logger writes it as one line of a JSON Lines file when file logging is enabled, hands it to the registered sinks and prints it when screen output is enabled for its channel.
Role code imports log and calls the method of a channel:
from unaiverse.utils.logger import log
log.user("Lecture 2 of 3") # Always recorded and printed
log.network("peer connected", sub="pub", peer="peer-42")
log.debug("next sample", sub="prv", index=17) # Recorded only when DEBUG is on
log.critical("No data folder configured") # Recorded, then raises GenException
The node creates the logger when it starts and chooses the channels from environment variables (see Configuration):
| Variable | Effect on the logger |
|---|---|
NODE_PRINT |
1 records every channel. 0 (default) records only CRITICAL, ERROR and USER. |
NODE_LOG_CHANNELS |
A comma-separated list of channel names (case-insensitive) recorded together with the three channels that are always on. Unknown names are ignored. When it is not empty it replaces the choice of NODE_PRINT. |
NODE_SCREEN_BASIC_PRINT |
1 prints only the three channels always on. The other recorded channels still reach the file and the sinks. |
NODE_LOG |
1 writes the records to the file <script name>.jsonl (for example run_world.py.jsonl) in the folder of the script that started the process. |
NODE_LOG_APPEND |
1 appends to that file. 0 (default) truncates it at every start. |
NODE_LOG_SINK_MODULE |
The import path of a module with a function attach(log). The node imports it after creating the logger and calls attach(log). A failure is logged on ERROR and the node continues. |
NODE_LIBP2PLOG |
1 captures the raw output of the native networking library on the P2P channel. |
A record has these fields:
| Field | Content |
|---|---|
ts |
The time in ISO 8601 (UTC with milliseconds). Once the node passes its clock to set_clock, the time comes from that clock. |
ch |
The channel name, such as "NETWORK". |
cy |
The cycle of the clock of the node (0 before set_clock is called). |
ctx |
The context dict that set_ctx keeps across records. |
msg |
The message. |
sub |
The subdomain tag: "pub" (the public network), "prv" (the network of the world) or "gen" (neither). |
info |
The dict of the keyword arguments of the call. Present only when the call had some. |
On screen a record of USER, ERROR or CRITICAL prints as the bare message in its color. The other channels print as [CHANNEL ] HH:MM:SS.mmm cy=<cycle> | <ctx> {<sub>} <message> [<info>]. The screen output skips a message equal to the last one printed unless the call passes rep=True. It also turns <br/> into a new line, drops <strong> and prints a link <a href="u">t</a> as t (u). An interactive block prints as its plain text. Colors are disabled when the standard output is not a terminal.
Ch
¶
Bases: str, Enum
The enumeration of the channels. Each member is a str equal to its name.
| Member | Content | Recorded by default |
|---|---|---|
CRITICAL |
Fatal conditions. log.critical also raises GenException. |
always |
ERROR |
Errors and warnings that do not stop the node. | always |
USER |
The output meant for the person who runs the node. | always |
NETWORK |
Connections, disconnections and message routing. | with NODE_PRINT=1 |
SESSION |
Dialing, handshake, keep-alive, reconnection and close of each session. | with NODE_PRINT=1 |
CPOOL |
The connection pool: slots, evictions and limits. | with NODE_PRINT=1 |
INTER |
Interactions between nodes. | with NODE_PRINT=1 |
STREAMS |
The flow of stream data. | with NODE_PRINT=1 |
STATEM |
A snapshot of the state of the node and of the behavior at every tick. | with NODE_PRINT=1 |
MISC |
Everything else. log(...) writes here too. |
with NODE_PRINT=1 |
DEBUG |
Fine-grained diagnostics. | with NODE_PRINT=1 |
P2P |
The raw output of the native networking library. | with NODE_PRINT=1 and NODE_LIBP2PLOG=1 |
ALWAYS_ON_CHANNELS
module-attribute
¶
frozenset({Ch.CRITICAL, Ch.ERROR, Ch.USER}). These channels are always recorded and always printed. disable, disable_screen and disable_all_screen never turn them off.
EXTRA_CHANNELS
module-attribute
¶
EXTRA_CHANNELS: frozenset[Ch] = frozenset({Ch.NETWORK, Ch.STREAMS, Ch.INTER, Ch.MISC, Ch.DEBUG, Ch.STATEM, Ch.CPOOL, Ch.P2P, Ch.SESSION})
The frozenset of the nine other channels.
ALL_CHANNELS
module-attribute
¶
ALL_CHANNELS: frozenset[Ch] = frozenset(ALWAYS_ON_CHANNELS | EXTRA_CHANNELS)
The frozenset of all twelve channels.
"pub", the tag of the records about the public network.
"prv", the tag of the records about the network of the world.
"gen", the tag of the records about neither network. A record without an explicit or sticky tag gets this one.
Logger
¶
The class of log. It holds the real logger and forwards every attribute access to it. Until create is called there is no real logger. In that phase critical prints the message and raises GenException while any other method prints its positional arguments with print and ignores the keyword arguments. Code that logs before the node starts (a processor built before Node(...)) therefore still shows its messages.
Once created, log offers the methods below. Each logging method takes msg: str, sub: str = "" and any keyword argument. The keyword arguments become the info of the record. An empty sub takes the sticky tag of set_sub and falls back to "gen" when there is none.
| Method | Effect |
|---|---|
critical(msg, sub="", **info) |
Records on CRITICAL and raises unaiverse.custom.GenException(msg). |
error, user, statem, network, streams, inter, misc, debug, cpool, session |
Records on the channel of the same name. |
p2p(msg, sub="", **info) |
Records on P2P without the first 43 characters of msg (the timestamp prefix of the native library). |
log(msg, sub="", **info) |
Calling the object records on MISC. |
enable(*channels), disable(*channels) |
Turns the recording of channels on or off. The three channels always on stay on. |
enable_screen(*channels), disable_screen(*channels), disable_all_screen() |
Turns the screen output of channels on or off. A channel that is not recorded never prints. |
set_verbose_screen(verbose) |
True prints the full record for USER, ERROR and CRITICAL too. |
set_plain_msg_only(yes_or_no) |
True prints the bare message for every channel. |
set_file_enabled(enabled) |
Turns the writing of the file on or off at runtime. Turning it on opens the file when it is closed. |
set_sub(sub), clear_sub() |
Gives a sticky subdomain tag to the following records of the current asyncio task. Each task of the node keeps its own tag. |
set_ctx(**kwargs), clear_ctx(*keys) |
set_ctx merges keys into the context of every record and clear_ctx removes them (all of them without arguments). |
set_clock(clock) |
Takes the time and the cycle of the records from the clock of the node. The node calls it. |
add_record_sink(fn), remove_record_sink(fn) |
Registers or removes a sink (below). |
set_name(name) |
Replaces the stored name. The file keeps its path. |
inspector_enabled(flag), get_inspector_console() |
Keeps the last 20 messages of the always-on channels (HTML-escaped) for the inspector of the node. get_inspector_console() returns them in order from the oldest as {"output_messages": [...]}. |
close() |
Flushes and closes the file. The logger is also a context manager that closes on exit. |
A sink is a function fn(channel_name: str, record: dict) that the logger calls for every record of a recorded channel before the screen output. It runs while the logger holds its lock and must not block (no network or file I/O). An exception raised by a sink is ignored. The record is the dict that the screen output modifies afterwards (it rewrites msg). A sink that keeps records should copy them.
# my_sink.py, loaded with NODE_LOG_SINK_MODULE=my_sink
import collections
errors = collections.deque(maxlen=100)
def attach(log):
log.add_record_sink(lambda ch, rec: errors.append(dict(rec)) if ch == "ERROR" else None)
create
¶
Creates the real logger. The node calls it once in Node.__init__. The keyword arguments are these:
| Argument | Type | Default | Meaning |
|---|---|---|---|
name |
str |
"app" |
The base name of the file <name>.jsonl. The node passes the file name of the script. |
log_dir |
str or Path |
"logs" |
The folder of the file. The logger creates it when missing even when file logging is disabled. The node passes the folder of the script. |
active |
set[Ch] or None |
None |
The recorded channels. The three always-on channels are added in every case and None records only them. |
screen |
set[Ch] or None |
None |
The channels printed on screen. None prints every recorded channel. |
no_color |
bool |
False |
True prints without ANSI colors. |
verbose_screen |
bool |
False |
True prints the full record for every channel. |
file_enabled |
bool |
True |
True writes the file. The node passes the value of NODE_LOG. |
file_append |
bool |
False |
True appends to the file. The node passes the value of NODE_LOG_APPEND. |
A second call replaces the logger without closing the file of the first one.
set_print_fcn
¶
Replaces the function that prints the records of one channel and one subdomain on screen. The arguments are print_fcn, ch (a Ch, or None for all channels), sub ("pub", "prv", "gen" or None for all), supports_html and supports_uai_blocks (default False). The logger calls print_fcn(text, file=sys.stdout, flush=True). With supports_html=True the text keeps its HTML. With supports_uai_blocks=True the interactive blocks reach the function unchanged. Before create the call raises AttributeError.
The shared Logger of the process. Every module of the SDK imports this object and the node creates the real logger behind it. A program that runs no node can call log.create(...) itself.