Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python logging: is it possible to add module name to formatter

Tags:

python

It is possible to get a logger by module name. Like this:

logging.getLogger(module_name)

I would like to add module_name to every log record. Is it possible to set up a Formatter object which adds module_name?

like image 497
Alexander Putilin Avatar asked Aug 19 '14 20:08

Alexander Putilin


People also ask

What does logging getLogger (__ Name __?

To start logging using the Python logging module, the factory function logging. getLogger(name) is typically executed. The getLogger() function accepts a single argument - the logger's name. It returns a reference to a logger instance with the specified name if provided, or root if not.

Is logging a module in Python?

Python comes with a logging module in the standard library that provides a flexible framework for emitting log messages from Python programs. This module is widely used by libraries and is the first go-to point for most developers when it comes to logging.


2 Answers

You are looking for the %(name)s parameter; add that to your formatter pattern:

FORMAT = "%(name)s: %(message)s"
logging.basicConfig(format=FORMAT)

or when creating a Formatter():

FORMAT = "%(name)s: %(message)s"
formatter = logging.Formatter(fmt=FORMAT)

See the LogRecord attributes reference:

Attribute name: name
Format: %(name)s
Description: Name of the logger used to log the call.

like image 122
Martijn Pieters Avatar answered Sep 17 '22 23:09

Martijn Pieters


when you initialize the logger (only need to do this once for the app) try this config

logging.basicConfig(
    filename='var/bpextract.log',
    level=logging.INFO,
    format='%(asctime)s  %(process)-7s %(module)-20s %(message)s',
    datefmt='%m/%d/%Y %H:%M:%S'
    )

...later in your code...

log = logging.getLogger("bpextract")
log.info('###### Starting BPExtract App #####')
like image 36
kkelly18 Avatar answered Sep 20 '22 23:09

kkelly18