Example for configuring logging in Python 3 using a JSON file.
If you run example.py
as it is, then you will get the following output:
INFO:root:This is the logger configured by `logging.basicConfig()`.
INFO ; 2014-10-18 15:17:38,278; root ; This is an INFO message on the root logger.
WARNING ; 2014-10-18 15:17:38,278; child ; This is a WARNING message on the child logger.
ERROR ; 2014-10-18 15:17:38,278; child ; This is an ERROR message.
--- Logging error ---
Traceback (most recent call last):
File "/usr/lib/python3.4/logging/handlers.py", line 971, in emit
smtp = smtplib.SMTP(self.mailhost, port, timeout=self.timeout)
File "/usr/lib/python3.4/smtplib.py", line 242, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python3.4/smtplib.py", line 321, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python3.4/smtplib.py", line 292, in _get_socket
self.source_address)
File "/usr/lib/python3.4/socket.py", line 509, in create_connection
raise err
File "/usr/lib/python3.4/socket.py", line 500, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
Call stack:
File "foo.py", line 44, in <module>
main()
File "foo.py", line 29, in main
child.error("This is an ERROR message.")
Message: 'This is an ERROR message.'
Arguments: ()
This traceback is not a related to our application. It has to do with the logging configuration. More specifically we have set an smtp
handler that tries to send an email using a MailServer that runs on 127.0.0.1:25
, but there is no server listening to that ip/port. While developing, we can easily setup such a server by running the following command on a separate console session:
sudo python -m smtpd -n -c DebuggingServer localhost:25
Needless to say, on production we should set up a proper MailServer. Anyway, now, if we execute the script we will get the following output:
INFO:root:This is the logger configured by `logging.basicConfig()`.
INFO ; 2014-10-18 15:17:51,078; root ; This is an INFO message on the root logger.
WARNING ; 2014-10-18 15:17:51,079; child ; This is a WARNING message on the child logger.
ERROR ; 2014-10-18 15:17:51,079; child ; This is an ERROR message.
while, on the console that runs the Mail Server we will get the following output:
---------- MESSAGE FOLLOWS ----------
From: [email protected]
To: [email protected]
Subject: Something went wrong
Date: Sat, 18 Oct 2014 12:17:51 -0000
X-Peer: 127.0.0.1
thread: MainThread
Level: ERROR
Time: 2014-10-18 15:17:51,079
Location: foo.py:29
Method: main
Message:
This is an ERROR message.
------------ END MESSAGE ------------