bohicalog
The BOHICA Logging Library provides a configured logger for your module or application.
- setup_logger(name='bohicalog', logfile=None, level=10, formatter=None, maxbytes=0, backupcount=0, fileloglevel=None, disablestderrlogger=False, isrootlogger=False, json=False, json_ensure_ascii=False)[source]
Configures and returns a fully configured logger instance, no hassles. If a logger with the specified name already exists, it returns the existing instance, else creates a new one.
If you set the
logfileparameter with a filename, the logger will save the messages to the logfile, but does not rotate by default. If you want to enable log rotation, set bothmaxBytesandbackupCount.Usage:
from BOHICALOG import setup_logger logger = setup_logger() logger.info("hello")
- Parameters
name (string) – Name of the Logger object. Multiple calls to
setup_logger()with the same name will always return a reference to the same Logger object. (default:__name__)logfile (string) – If set, also write logs to the specified filename.
level (int) – Minimum logging-level to display (default:
DEBUG).formatter (Formatter) – Python logging Formatter object (by default uses the internal LogFormatter).
maxbytes (int) – Size of the logfile when rollover should occur. Defaults to 0, rollover never occurs.
backupcount (int) – Number of backups to keep. Defaults to 0, rollover never occurs.
fileloglevel (int) –
Minimum logging-level for the file logger (is not set, it will use the loglevel from the
levelargument)disablestderrlogger (bool) – Should the default stderr logger be disabled. Defaults to False.
isrootlogger (bool) – If True then returns a root logger. Defaults to False. (see also the Python docs).
json (bool) – If True then log in JSON format. Defaults to False. (uses python-json-logger).
json_ensure_ascii (bool) – Passed to json.dumps as ensure_ascii, default: False (if False: writes utf-8 characters, if True: ascii only representation of special characters - eg. ‘Öß’)
- Returns
A fully configured Python logging Logger object you can use with
.debug("msg"), etc.
- class LogFormatter(color=True, fmt='%(color)s[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]%(end_color)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', colors={10: '\x1b[36m', 20: '\x1b[32m', 30: '\x1b[33m', 40: '\x1b[31m', 50: '\x1b[31m'})[source]
Log formatter used in Tornado. Key features of this formatter are: * Color support when logging to a terminal that supports it. * Timestamps on every log line. * Robust against str/bytes encoding problems.
- Parameters
color (bool) – Enables color support.
fmt (string) – Log message format. It will be applied to the attributes dict of log records. The text between
%(color)sand%(end_color)swill be colored depending on the level if color support is on.colors (dict) – color mappings from logging level to terminal color code
datefmt (string) – Datetime format. Used for formatting
(asctime)placeholder inprefix_fmt.
Changed in version 3.2: Added
fmtanddatefmtarguments.
- to_unicode(value)[source]
Converts a string argument to a unicode string. If the argument is already a unicode string or None, it is returned unchanged. Otherwise it must be a byte string and is decoded as utf8.
- setup_default_logger(logfile=None, level=10, formatter=None, maxBytes=0, backupCount=0, disableStderrLogger=False)[source]
Deprecated. Use BOHICALOG.loglevel(..), BOHICALOG.logfile(..), etc.
Globally reconfigures the default BOHICALOG.logger instance.
Usage:
from BOHICALOG import logger, setup_default_logger setup_default_logger(level=WARN) logger.info("hello") # this will not be displayed anymore because minimum loglevel was set to WARN
- Parameters
logfile (string) – If set, also write logs to the specified filename.
level (int) –
Minimum logging-level to display (default: DEBUG).
formatter (Formatter) –
Python logging Formatter object (by default uses the internal LogFormatter).
maxBytes (int) – Size of the logfile when rollover should occur. Defaults to 0, rollover never occurs.
backupCount (int) – Number of backups to keep. Defaults to 0, rollover never occurs.
disableStderrLogger (bool) – Should the default stderr logger be disabled. Defaults to False.
- loglevel(level=10, update_custom_handlers=False)[source]
Set the minimum loglevel for the default logger (BOHICALOG.logger) and all handlers.
This reconfigures only the internal handlers of the default logger (eg. stream and logfile). You can also update the loglevel for custom handlers by using update_custom_handlers=True.
- Parameters
level (int) –
Minimum logging-level to display (default: DEBUG).
update_custom_handlers (bool) – If you added custom handlers to this logger and want this to update them too, you need to set update_custom_handlers to True
- formatter(formatter, update_custom_handlers=False)[source]
Set the formatter for all handlers of the default logger (
BOHICALOG.logger).This reconfigures only the BOHICALOG internal handlers by default, but you can also reconfigure custom handlers by using
update_custom_handlers=True.Beware that setting a formatter which uses colors also may write the color codes to logfiles.
- Parameters
formatter (Formatter) –
Python logging Formatter object (by default uses the internal LogFormatter).
update_custom_handlers (bool) – If you added custom handlers to this logger and want this to update them too, you need to set
update_custom_handlersto True
- logfile(filename, formatter=None, mode='a', maxBytes=0, backupCount=0, encoding=None, loglevel=None, disableStderrLogger=False)[source]
Setup logging to file (using a RotatingFileHandler internally).
By default, the file grows indefinitely (no rotation). You can use the
maxbytesandbackupcountvalues to allow the file to rollover at a predetermined size. When the size is about to be exceeded, the file is closed and a new file is silently opened for output. Rollover occurs whenever the current log file is nearlymaxbytesin length; if either ofmaxbytesorbackupcountis zero, rollover never occurs.If
backupcountis non-zero, the system will save old log files by appending the extensions ‘.1’, ‘.2’ etc., to the filename. For example, with abackupcountof 5 and a base file name of app.log, you would get app.log, app.log.1, app.log.2, up to app.log.5. The file being written to is always app.log. When this file is filled, it is closed and renamed to app.log.1, and if files app.log.1, app.log.2, etc. exist, then they are renamed to app.log.2, app.log.3 etc. respectively.- Parameters
filename (string) – Filename of the logfile. Set to None to disable logging to the logfile.
formatter (Formatter) –
Python logging Formatter object (by default uses the internal LogFormatter).
mode (string) – mode to open the file with. Defaults to
amaxBytes (int) – Size of the logfile when rollover should occur. Defaults to 0, rollover never occurs.
backupCount (int) – Number of backups to keep. Defaults to 0, rollover never occurs.
encoding (string) – Used to open the file with that encoding.
loglevel (int) – Set a custom loglevel for the file logger, else uses the current global loglevel.
disableStderrLogger (bool) – Should the default stderr logger be disabled. Defaults to False.
- syslog(logger_to_update=<Logger bohicalog_default (DEBUG)>, facility=1, disableStderrLogger=True)[source]
Setup logging to syslog and disable other internal loggers Configure a SysLogHandler to log to syslog. This will disable the default stderr logger. :param logger_to_update: the logger to enable syslog logging for :param facility: syslog facility to log to :param disableStderrLogger: should the default stderr logger be disabled? defaults to True :return the new SysLogHandler, which can be modified externally (e.g. for custom log level)
- json(enable=True, json_ensure_ascii=False, update_custom_handlers=False)[source]
Enable/disable json logging for all handlers.
Params: * json_ensure_ascii … Passed to json.dumps as ensure_ascii, default: False (if False: writes utf-8 characters, if True: ascii only representation of special characters - eg. ‘Öß’)
https://github.com/madzak/python-json-logger
This library is provided to allow standard python logging to output log data as JSON formatted strings
- merge_record_extra(record, target, reserved)[source]
Merges extra attributes from LogRecord object into target dictionary
- Parameters
record – logging.LogRecord
target – dict to update
reserved – dict or list with reserved keys to skip
- class JsonEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]
A custom encoder extending the default JSONEncoder
Constructor for JSONEncoder, with sensible defaults.
If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped.
If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.
If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place.
If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.
If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.
If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.
If specified, separators should be an (item_separator, key_separator) tuple. The default is (’, ‘, ‘: ‘) if indent is
Noneand (‘,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘,’, ‘:’) to eliminate whitespace.If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a
TypeError.
- class JsonFormatter(*args, **kwargs)[source]
A custom formatter to format logging records as json strings. Extra values will be formatted as str() if not supported by json default encoder
- Parameters
json_default – a function for encoding non-standard objects as outlined in http://docs.python.org/2/library/json.html
json_encoder – optional custom encoder
json_serializer – a
json.dumps()-compatible callable that will be used to serialize the log record.json_indent – an optional
json.dumps()-compatible numeric value that will be used to customize the indent of the output json.prefix – an optional string prefix added at the beginning of the formatted string
rename_fields – an optional dict, used to rename field names in the output. Rename message to @message: {‘message’: ‘@message’}
json_indent – indent parameter for json.dumps
json_ensure_ascii – ensure_ascii parameter for json.dumps
reserved_attrs – an optional list of fields that will be skipped when outputting json log record. Defaults to all log record attributes: http://docs.python.org/library/logging.html#logrecord-attributes
timestamp – an optional string/boolean field to add a timestamp when outputting the json log record. If string is passed, timestamp will be added to log record using string as key. If True boolean is passed, timestamp key will be “timestamp”. Defaults to False/off.
- parse()[source]
Parses format string looking for substitutions
This method is responsible for returning a list of fields (as strings) to include in all log messages.
- add_fields(log_record, record, message_dict)[source]
Override this method to implement custom logic for adding fields.
Source: https://github.com/tartley/colorama/blob/master/colorama/ansi.py Copyright: Jonathan Hartley 2013. BSD 3-Clause license.
- code_to_chars(code)[source]
Convert a color code to the corresponding ANSI escape sequence. :param code: :return:
Version information for bohicalog.
Run with python -m bohicalog.version