Python | Add Logging to a Python Script
Last Updated :
12 Jun, 2019
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files.
Code #1 : Using the logging module to add logging to a simple program
Python3 1==
import logging
def main():
# Configure the logging system
logging.basicConfig(filename ='app.log',
level = logging.ERROR)
# Variables (to make the calls that follow work)
hostname = 'www.python.org'
item = 'spam'
filename = 'data.csv'
mode = 'r'
# Example logging calls (insert into your program)
logging.critical('Host %s unknown', hostname)
logging.error("Couldn't find %r", item)
logging.warning('Feature is deprecated')
logging.info('Opening file %r, mode = %r', filename, mode)
logging.debug('Got here')
if __name__ == '__main__':
main()
- The five logging calls (critical(), error(), warning(), info(), debug()) represent different severity levels in decreasing order.
- The level argument to basicConfig() is a filter. All messages issued at a level lower than this setting will be ignored.
- The argument to each logging operation is a message string followed by zero or more arguments. When making the final log message, the % operator is used to format the message string using the supplied arguments.
If you run the code above, the contents of the file
app.log will be as follow -
CRITICAL:root:Host www.python.org unknown
ERROR:root:Could not find 'spam'
To change the output or level of output, change the parameters to the
basicConfig() call as in the code given below -
Code #2 :
Python3 1==
logging.basicConfig(
filename = 'app.log',
level = logging.WARNING,
format = '%(levelname)s:%(asctime)s:%(message)s')
Output :
CRITICAL:2012-11-20 12:27:13, 595:Host www.python.org unknown
ERROR:2012-11-20 12:27:13, 595:Could not find 'spam'
WARNING:2012-11-20 12:27:13, 595:Feature is deprecated
The logging configuration is hardcoded directly into the program. To configure it from a configuration file, change the
basicConfig() call to the following.
Code #3 :
Python3 1==
import logging
import logging.config
def main():
# Configure the logging system
logging.config.fileConfig('logconfig.ini')
...
Now make a configuration file that looks like this -
[loggers]
keys=root
[handlers]
keys=defaultHandler
[formatters]
keys=defaultFormatter
[logger_root]
level=INFO
handlers=defaultHandler
qualname=root
[handler_defaultHandler]
class=FileHandler
formatter=defaultFormatter
args=('app.log', 'a')
[formatter_defaultFormatter]
format=%(levelname)s:%(name)s:%(message)s
If you want to make changes to the configuration, you can simply edit the file as appropriate.
Ignoring for the moment that there are about a million advanced configuration options for the logging module, this solution is quite sufficient for simple programs and scripts. Simply make sure to execute the
basicConfig()
call prior to making any logging calls, and the program will generate logging output.
Reference: https://docs.python.org/3/howto/logging-cookbook.html
Similar Reads
Python | Add Logging to Python Libraries In this article, we will learn how to add a logging capability to a library, but donât want it to interfere with programs that donât use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : Python3 #
2 min read
How to Exit a Python script? In this article, we are going to see How to Exit Python Script. Exiting a Python script refers to the termination of an active Python process. In this article, we will take a look at exiting a Python program, performing a task before exiting the program, and exiting the program while displaying a cu
4 min read
Python | Logging Test Output to a File Problem - Writing the results of running unit tests to a file instead of printed to standard output. A very common technique for running unit tests is to include a small code fragment (as shown in the code given below) at the bottom of your testing file. Code #1 : Python3 1== import unittest class M
2 min read
How to run bash script in Python? If you are using any major operating system, you are indirectly interacting with bash. If you are running Ubuntu, Linux Mint, or any other Linux distribution, you are interacting with bash every time you use the terminal. Suppose you have written your bash script that needs to be invoked from python
2 min read
How to Run a Python Script Python scripts are Python code files saved with a .py extension. You can run these files on any device if it has Python installed on it. They are very versatile programs and can perform a variety of tasks like data analysis, web development, etc. You might get these Python scripts if you are a begin
6 min read
How To Embed Python Code In Batch Script Embedding Python code in a batch script can be very helpful for automating tasks that require both shell commands and Python scripting. In this article, we will discuss how to embed Python code within a batch script. What are Batch Scripts and Python Code?Batch scripts are text files containing a se
4 min read
Python | Accepting Script Input A lot of people use Python as a replacement for shell scripts, using it to automate common system tasks, such as manipulating files, configuring systems, and so forth. This article aims to describe accepting Script Input via Redirection, Pipes, or Input Files. Problem - To have a script to be able t
2 min read
Script management with Python Poetry Poetry is a tool that makes it easier to manage Python dependencies and packages and create virtual environments for a project, as well as to package and distribute Python libraries. Apart from dependency management, script management is also one of the strong features of Poetry where developers can
5 min read
Autorun a Python script on windows startup Adding a Python script to windows start-up basically means the python script will run as the windows boots up. This can be done by two step process - Step #1: Adding script to windows Startup folder After the windows boots up it runs (equivalent to double-clicking) all the application present in its
2 min read
How to Run a Python Script using Docker? Docker helps you to run your Python application very smoothly in different environments without worrying about underlying platforms. Once you build an image using dockerfile you can run that image wherever you want to run. Docker image will help you to package all the dependencies required for the a
8 min read