Logging to stdout in Python
This tutorial shows how to write logs to files and stdout in Python.
logging.basicConfig()
Log in to
thestdout
If we want to print the logs to the console window and write the logs to a file, we can use logging.basicConfig()
the log_log function to accomplish this process. logging.basicConfig()
The log_log function configures some basic parameters for logging in Python. We can use stream
the log_log parameter of this function to specify that we also want to print this log on the console window. The rest of the configuration logging.basicConfig()
is the same as using the log_log function to write the logs to a file. The following code demonstrates how we can write logs to the console window.
import logging
import sys
# Creating and Configuring Logger
Log_Format = "%(levelname)s %(asctime)s - %(message)s"
logging.basicConfig(
filename="logfile.log",
stream=sys.stdout,
filemode="w",
format=Log_Format,
level=logging.ERROR,
)
logger = logging.getLogger()
# Testing our Logger
logger.error("Our First Error Message")
Output:
2021-06-13 05:15:24,093 - root - ERROR - Our First Error Message
logging.StreamHandler()
Log in to
thestdout
We can also logging.StreamHandler()
write logs to the console window in Python using the logger function. By passing sys.stdout
to logging.StreamHandler()
the logger function, we can create a stream handler that can print log messages to the console window. We can then addHandler()
add this stream handler to our logger object using the logger function. The following code snippet shows us how to use logging.StreamHandler()
the logger function to print log messages to the console window.
import logging
import sys
logger = logging.getLogger()
fileHandler = logging.FileHandler("logfile.log")
streamHandler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
streamHandler.setFormatter(formatter)
fileHandler.setFormatter(formatter)
logger.addHandler(streamHandler)
logger.addHandler(fileHandler)
logger.error("This is the first error")
Output:
2021-06-13 05:03:37,510 - root - ERROR - This is the first error
In the code above, we use the logging.FileHandler()
and logging.StreamHandler()
functions to write log messages This is the first error
to a file logfile.log
and the console window. We first created a logger object, which we will use logging.getLogger()
to write logs using the function. Then, we created a file handler fileHandler
and assigned it logging.FileHandler('logfile.log')
.
After that, we created a stream handler streamHandler
and assigned logging.StreamHandler(sys.stdout)
. After that, we created a formatter to logging.Formatter()
format our output using the function and set the formatter setFormatter()
for fileHandler
and streamHandler
using the function. Following the previous step, we addHandler()
added two new handlers to our logger object using the function. Finally, we used to logger.error('This is the first error')
write error messages to our file and console window.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Implementing a Low-Pass Filter in Python
Publish Date:2025/05/07 Views:89 Category:Python
-
Low pass filter is a term in signal processing basics and is often used to filter signals to obtain more accurate results. This tutorial will discuss the low-pass filter and how to create and implement it in Python. A low-pass filter is use
Implementing Curl command in Python using requests module
Publish Date:2025/05/07 Views:97 Category:Python
-
requests This article will discuss and implement different curl commands using the module in Python . requests Installing modules in Python Python provides us with requests the module to execute curl command. Install it in Python 3 using Pi
Using fetchall() in Python to extract elements from a database
Publish Date:2025/05/07 Views:171 Category:Python
-
This article aims to describe fetchall() the working methods of extracting elements from a database using and how to display them correctly. This article will also discuss list(cursor) how functions can be used in programs. fetchall() Extra
Parsing log files in Python
Publish Date:2025/05/07 Views:106 Category:Python
-
Log files contain information about events that occurred during the operation of a software system or application. These events include errors, requests made by users, bugs, etc. Developers can further scan these usage details to find poten
Declaring a variable without a value in Python
Publish Date:2025/05/07 Views:57 Category:Python
-
A variable is a reserved memory location that can store some value. In other words, variables in a Python program provide data to the computer to process operations. Every value in Python has a data type. There are numbers, lists, tuples, e
Defining class global variables in Python
Publish Date:2025/05/07 Views:81 Category:Python
-
A global variable is a variable that is visible and available in every part of the program. Global variables are also not defined in any function or method. On the other hand, local variables are defined in functions and can be used only in
Incrementing loop step by 2 in Python
Publish Date:2025/05/07 Views:199 Category:Python
-
In each iteration, for the loop increases the counter variable by a constant. A loop with the sequence 0, 2, 4, 6 for will increase the counter variable by 2 each iteration. This article will show you some for ways to increment by 2 in a lo
Pool map with multiple parameters in Python
Publish Date:2025/05/07 Views:104 Category:Python
-
multiprocessing This article will explain different ways to perform parallel function execution using the module in Python . multiprocessing The module provides functionality to perform parallel function execution using multiple inputs and
Python if...else in Lambda function
Publish Date:2025/05/07 Views:68 Category:Python
-
lambda Functions are used to implement some simple logic in Python and can be thought of as anonymous functions. It can have multiple parameters but only one expression, just def like any other function defined using the keyword. We can def