Alexander Putilin
Alexander Putilin

Reputation: 2342

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

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?

Upvotes: 15

Views: 14043

Answers (3)

kkelly18
kkelly18

Reputation: 518

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 #####')

Upvotes: 4

jh314
jh314

Reputation: 27812

In logging.basicConfig, you can specify the format:

logging.basicConfig(format='%(name)s\t%(message)s')

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1123830

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.

Upvotes: 21

Related Questions