mudpi / mudpi-core

Configurable automation library for linux SBC boards including raspberry pi
https://mudpi.app
275 stars 40 forks source link

Logging Class (using Python's logging module) #12

Closed P33ry closed 3 years ago

P33ry commented 4 years ago

Changes

New Logger Class

Created logger/Logger.py which is to be initialized by mudpi.py early on. To avoid the complications of passing an instance around of the logger the current logger instance is a static member on the Logger Class (see Logger.logger).

To ease and shorten access even further I've added static methods that direct their parameters to this Logger instance. So that Logger.log(someLevel, someMessage) suffices (assuming prior initialization).

Logger Usage

The logger/Logger.py introduces a dictionary for access to the log levels. When logging all messages are written also to a log file (if set up in the configs) with a different format [%(asctime)s][%(name)s][%(levelname)s] %(message)s while they are printed unedited to stdout.

The logging module allows to place different logging levels for each handler (stdout or log file) therefore for each a different log level is configurable.

Example

Code

Logger.log(LOG_LEVEL["info"], 'Initializing Logger...\t\t\t\033[1;32m Complete\033[0;0m')

stdout (Supports Text Color, just not in this post)

Initializing Logger...                   Complete

Log File (default mudpi.log)

[15:24:14][EVE][INFO] Initializing Logger...             Complete

Note: It is possible to just log to a file via Logger.log_to_file().

Config

"logging": {
        "file_log_level": "debug",
        "terminal_log_level": "debug",
        "file": "mudpi.log"
    },

I've edited the mudpi.config.example to include verbose logging defaults. If the logging levels are set higher the lower ones (debug, info, ...) are not printed/written.

If debugging is set to true in the configuration all logging levels are automatically set to "debug" regardless of the configuration.