Function

Logging to multiple destinations with different levels.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#https://docs.python.org/3.5/howto/logging-cookbook.html
import logging

# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
filename='myapp.log',
filemode='w')

# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)

# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')

# tell the handler to use this format
console.setFormatter(formatter)

# add the handler to the root logger
logging.getLogger('').addHandler(console)

# Now, we can log to the root logger, or any other logger. First the root...
logging.info('root logging')

# Now, define a couple of other loggers which might represent areas in your
# application:
logger1 = logging.getLogger('area1')
logger2 = logging.getLogger('area2')
logger1.debug('logger1')
logger1.info('logger1')
logger1.warning('logger1')
logger1.error('logger1')
logger2.debug('logger2')
logger2.info('logger2')
logger2.warning('logger2')
logger2.error('logger2')

Reference

[1] Python Cookbook