Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python logging to multiple files

Does someone has an example of logging in python to 2 or more different logfiles.

I want to log for example to '/tmp/foo.log' and '/tmp/bar.log'

Thanks in advance

T

like image 960
Hein Avatar asked Apr 07 '11 07:04

Hein


People also ask

What is logging getLogger (__ Name __)?

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. Multiple calls to getLogger() with the same name will return a reference to the same logger object.


2 Answers

Here's an example:

import logging
logger1 = logging.getLogger('1')
logger1.addHandler(logging.FileHandler('/tmp/logger1'))
logger2 = logging.getLogger('2')
logger2.addHandler(logging.FileHandler('/tmp/logger2'))

logger1.error('1')
logger2.error('2')

Then,

 $ cat /tmp/logger1
 1
 $ cat /tmp/logger2
 2
like image 163
David Avatar answered Sep 26 '22 20:09

David


Here's a complete working example based on the example in logging.html. The main 'gotcha' to note is that you have to be sure to set the log level for the root logger to interact correctly with the files.

import logging

logging.getLogger('').setLevel(logging.DEBUG)
def create_log_file(filename, level=logging.INFO):
    handler = logging.FileHandler(filename)
    handler.setLevel(level)
    formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
    handler.setFormatter(formatter)
    logging.getLogger('').addHandler(handler)

create_log_file('/temp/log1.log', logging.DEBUG)
create_log_file('/temp/log2.log', logging.INFO)

# Now, we can log to the root logger, or any other logger. First the root...
logging.info('Jackdaws love my big sphinx of quartz.')

# Now, define a couple of other loggers which might represent areas in your
# application:

logger1 = logging.getLogger('myapp.area1')
logger2 = logging.getLogger('myapp.area2')

logger1.debug('Quick zephyrs blow, vexing daft Jim.')
logger1.info('How quickly daft jumping zebras vex.')
logger2.warning('Jail zesty vixen who grabbed pay from quack.')
logger2.error('The five boxing wizards jump quickly.')
like image 27
Duncan Avatar answered Sep 25 '22 20:09

Duncan