python logging
Python hosting: Host, run, and code Python in the cloud!
Python logging
We can track events in a software application, this is known as logging. Let’s start with a simple example, we will log a warning message.
As opposed to just printing the errors, logging can be configured to disable output or save to a file. This is a big advantage to simple printing the errors.
Related course
Python Programming Bootcamp: Go from zero to hero
Logging example
import logging |
This will output:
WARNING:root:This is a warning! |
We can easily output to a file:
import logging |
The importance of a log message depends on the severity.
Level of severity
The logger module has several levels of severity. We set the level of severity using this line of code:
logging.basicConfig(level=logging.DEBUG) |
These are the levels of severity:
Type | Description |
---|---|
DEBUG | Information only for problem diagnostics |
INFO | The program is running as expected |
WARNING | Indicate something went wrong |
ERROR | The software will no longer be able to function |
CRITICAL | Very serious error |
import logging |
Time in log
You can enable time for logging using this line of code:
logging.basicConfig(format='%(asctime)s %(message)s') |
An example below:
import logging |
Output:
2015-06-25 23:24:01,153 Logging app started |
Related course
Python Programming Bootcamp: Go from zero to hero
Posted in beginner
Leave a Reply:
Got this error 'module' object has no attribute 'warning'
Hi, which code and python version are you using?
Hi Frank,
I use 2.7.9. I found it. It's due to my filename logging.py
So if I understand, It's not good to give the same name as a library to my own file.
I got the same problem with example on random numbers.
Thank you so much.
logging.basicConfig(filename='program.log',level=logging.DEBUG) #I don't understand this line .where can I find the file'program.log'?
Hi Tim, this file is created when running the program. You will find it in the same directory of your python program after running.
Hi,
I'm using Python 3.4 and do not get any program.log file inside of my .py folder nor anywhere else in the user folder. Can you tell me why?
Also, I would like to know is there a logging level where you can set to pick all logged messages except INFO or something like that?
Hi, this seems to be something platform specific. I tried the code on Python 3.4 and it outputed the file. Which operating system / platform do you use? You could try hardcoding the path to the file. Does logging to the console work?
If you want to ignore info you could simply raise the logging level. The warning, error and critical level will ignore the info and debug messages.
I'm doing this on a Linux machine (Linux Mint 17.2, specifically) and you have to run this with superuser privileges in order for it to work. :) Most will know that...but I'm a Linux noob so I thought I would point it out just in case.
So, to run it:
sudo python your_file_name.py
Thanks!