Simple logging framework.
Project description
logpie
A versatile logging framework.
Simple, efficient, and configurable logging framework to manage and streamline your application logs.
Installation:
python -m pip install [--upgrade] logpie
Key Features:
- Supports both file-based and console logging.
- Allows chronological organization of log files by year and month.
- Automatic log file cycling based on file size.
- Thread-safe operations for reliable logging.
- Customize your logs with configurable formatters.
- Can prefix log files with dates for easy tracking.
Usage:
# -*- coding: UTF-8 -*-
from logpie import Logger
log = Logger("my_logger")
if __name__ == '__main__':
log.debug("Testing debug messages...")
log.info("Testing info messages...")
log.warning("Testing warning messages...")
log.error("Testing error messages...")
log.critical("Testing critical messages...")
Components:
class logpie.Logger
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
name |
str |
logpie |
The name of the logger. The name of the logger cannot be changed after instantiation! |
level |
Level |
NOTSET |
The severity level for this logger. |
handlers |
Handler |
StreamHandler |
A handler or a tuple of handlers for this logger. |
Methods:
-
nameA property that returns the name of the logger.
NOTE:
Cannot be changed after instantiation!
-
levelA property that returns the severity level used by the logger.
-
level.setterSets the attribute
levelof the logger to value. All other messages with severity level less than this value will be ignored. By default, the logger is instantiated with severity levelNOTSET(0) and therefore all messages are logged.Available levels:
DEBUGINFOWARNINGERRORCRITICAL
-
handlersA property that returns the handlers used by the logger.
-
handlers.setterSets the logging handlers for the logger.
Available handlers:
StreamHandlerFileHandler
-
add_handler(value: Handler)Add a handler to the logger.
-
remove_handler(value: Handler)Remove a handler from the logger.
-
has_handlersCheck if the logger instance has any handlers.
-
close()Close the handlers of the logger and release the resources.
-
debug(msg: str, *args, **kwargs)Log a
msg % argswith levelDEBUG. To add exception info to the message use theexc_infokeyword argument with a True value.Example:
log.debug("Testing '%s' messages!", "DEBUG", exc_info=True)
or
log.debug("Testing '%(level)s' messages!", {"level": "DEBUG"}, exc_info=True)
-
info(msg: str, *args, **kwargs)Log a
msg % argswith levelINFO. To add exception info to the message use theexc_infokeyword argument with a True value.Example:
log.info("Testing '%s' messages!", "INFO", exc_info=True)
or
log.info("Testing '%(level)s' messages!", {"level": "INFO"}, exc_info=True)
-
warning(msg: str, *args, **kwargs)Log a
msg % argswith levelWARNING. To add exception info to the message use theexc_infokeyword argument with a True value.Example:
log.warning("Testing '%s' messages!", "WARNING", exc_info=True)
or
log.warning("Testing '%(level)s' messages!", {"level": "WARNING"}, exc_info=True)
-
error(msg: str, *args, **kwargs)Log a
msg % argswith levelERROR. To add exception info to the message use theexc_infokeyword argument with a True value.Example:
try: raise TypeError("Type error occurred!") except TypeError: log.error("Action failed!", exc_info=True)
or
try: raise TypeError("Type error occurred!") except TypeError as type_error: log.error("Action failed!", exc_info=type_error)
-
critical(msg: str, *args, **kwargs)Log a
msg % argswith levelCRITICAL. To add exception info to the message use theexc_infokeyword argument with a True value.Example:
try: raise TypeError("Critical error occurred!") except TypeError: log.critical("Action failed!", exc_info=True)
or
try: raise TypeError("Critical error occurred!") except TypeError as critical_error: log.critical("Action failed!", exc_info=critical_error)
Handlers:
By default, the logger streams all messages to the console output sys.stdout using the StreamHandler() handler.
To log messages into a file we must use the FileHandler() handler.
To use a different handler or more:
from logpie import Logger, StreamHandler, FileHandler
console = StreamHandler()
file = FileHandler("my_log_file.log")
log = Logger("my_logger", handlers=(console, file))
if __name__ == '__main__':
log.debug("Logging debug messages!")
class logpie.StreamHandler
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
formatter |
Formatter |
None |
Formatter object used to format the log messages. |
handle |
TextIO |
None |
The handle used to output the messages to the console. |
Methods:
-
handleA property that returns the handle in use.
-
handle.setterSet the handle used by the handler.
-
emit(row: Row)Emit a log row. This method acquires the thread lock and passes the log row formatted as a string to the
write()method. -
write(message: str)Write the log
messageusing the givenhandle.
class logpie.FileHandler
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
filename |
str |
None |
Name of the file to write logs into. |
mode |
str |
a |
Mode of file opening: a for appending and w for truncating the file. |
encoding |
str |
UTF-8 |
Encoding of the file. |
max_size |
int |
(1024 ** 2) * 4 (4 MB) |
Maximum size of the log file, in bytes. If cycle is enabled, when the file reaches the maximum size, the handler will switch to another file by incrementing the index with 1. |
cycle |
bool |
False |
Whether to cycle files when maximum size is reached. When the file reaches the maximum size, the handler will switch to another file by incrementing the index with 1. |
chronological |
bool |
False |
Whether to sort files chronologically. |
date_prefix |
bool |
False |
Whether to add date prefix to filename. |
date_aware |
bool |
False |
Whether to use date awareness to the log file. If date_prefix is enabled this will enforce the current date to be used rather than the date when the handler was created. |
formatter |
Formatter |
None |
Formatter object to format the logs. |
When chronological is enabled, the folder tree is by default structured as follows:
.
└─logs
└─year (ex: 2022)
└─month (ex: january)
├─2022-08-01_logpie.1.log
├─2022-08-01_logpie.2.log
└─2022-08-01_logpie.3.log
Methods:
-
emit(row: Row)Emit a log row. This method acquires the thread lock and passes the log
rowformatted as a string to thewrite()method. -
write(message: str)Write a log
messageinto the file.
class logpie.Formatter
The log rows are formatted with the help of the Formatter class.
Example:
from logpie import Logger, FileHandler, Formatter
# here we're also adding a new field (e.g. 'ip') used by the 'extra' keyword arguments.
my_formatter = Formatter(
row="${timestamp} - ${ip} - ${level} - ${source}: ${message}",
timestamp="[%Y-%m-%d %H:%M:%S.%f]",
stack="<${file}, ${line}, ${code}>",
)
my_handler = FileHandler("my_log_file.log", formatter=my_formatter)
log = Logger("my_logger", handlers=my_handler)
if __name__ == '__main__':
# here we are passing the 'ip' keyword argument for the 'extra' field
log.debug("Testing 'DEBUG' messages!", ip="192.168.1.100")
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
| row | str | '${timestamp} - ${level} - ${source}: ${message}' | The row formatting template. This template uses the string.Template style with placeholders (e.g. ${field}). |
| time | str | '[%Y-%m-%d %H:%M:%S.%f]' | The timestamp formatting template. This template uses the datetime.strftime() style (e.g. %Y-%m-%d %H:%M:%S.%f). |
| stack | str | '<${file}, ${line}, ${code}>' | The stack info formatting template. This template uses the string.Template style with placeholders (e.g. ${field}). |
Methods:
-
as_string(row: Row)Format a given row into a string based on predefined templates.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file logpie-5.0.1.tar.gz.
File metadata
- Download URL: logpie-5.0.1.tar.gz
- Upload date:
- Size: 14.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.0.0 CPython/3.10.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f1b1983724a4d14ce258f56c79c14290fdabcab1158012a55b4ce745f92e9e67
|
|
| MD5 |
ba008773a8686d1e0dbbb594d7a5b69b
|
|
| BLAKE2b-256 |
b08ff2e2b0ee6e539361dcc9252e94ba67e84eb6fb454c714ee648d74fcd4d45
|
File details
Details for the file logpie-5.0.1-py3-none-any.whl.
File metadata
- Download URL: logpie-5.0.1-py3-none-any.whl
- Upload date:
- Size: 13.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.0.0 CPython/3.10.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e9bffa4365021b5751be451633984fca392bcb198ec97b73dd777212eabc0d6c
|
|
| MD5 |
267110dbdf259df99fbccb47581038e2
|
|
| BLAKE2b-256 |
d097650f934af8b88cefcafb9d35ead85ef7784c4c842e224c460dd54679b32f
|