The example in this article describes how Python logging the console and file output logs at the same time. Share to everyone for your reference. Specifically as follows:
Python provides a very convenient log module that enables simultaneous output logs to the console and files.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#-*-
recently when doing automated testing, want to add a log to him, so use the logging module, the following is the Python add log several waysFirst, the Python code configuration (of course, there is a multi-module common Python code settings, this online there are many examples, it is not here to repeat)Import loggingIm
#!/usr/bin/env python#-*-coding:utf-8-*-#@Time: 2017/12/8 0008 14:30#@Author: MingImportLogginglogging.basicconfig ( level=logging. WARNING,#greater than or equal to warning level will be loggedformat='% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s', Datefmt='%a,%d%b%Y%h:%m:%s', filename='Myapp.log', FileMode='W',) Logging.debug ('This is debug message') Logging.info ('This is in
Label:Debug The first method is simple and straightforward, which is to print print out the variables that might be problematic: >>> def foo (s):
n= Int (s)
print ' >>> n =%d '% n
return 10/n
>>> def main (): C6/>foo (' 0 ')
>>> main ()
>>> n = 0
Traceback (most recent call last):
File " Assertion Where print is used to assist in viewing, you can replace it with an assertion (assert): >>> def foo (s):
N=int (s)
assertn!=0, ' n is zero '
return10/n
>>> def main ():
foo (' 0 ')
>>
. Streamhander (sys.stdout) Print_handler.setformatter (Formatter) # Add the specified log processing method to the instance, you can add multiple log processing methods Logger.addhandler ( File_handler) # Responsible for storing to file Logger.addhandler (Print_handler) # is responsible for printing to the screen # call logger, while the screen is displayed , save the log to file Logger.debug ("This is a Debug test") Logger.info ("This is an info test") logger.waring ("This is a Waring test") L
The Python standard log module uses Handler control log messages to write to different destinations, such as files, streams, messages, sockets, and so on. In addition to the Streamhandler, Filehandler, and Nullhandler definitions in the logging module, the other Handler are defined in the Logging.hangdlers module. These Handler are: Watchedfilehandler, Rotatingfilehandler, Timedrotatingfilehandler, Socketha
#-*-Coding:utf-8-*-Import loggingImport Sys# Gets the logger instance and returns root if the argument is empty loggerLogger = Logging.getlogger ("AppName")# Specify logger output formatFormatter = logging. Formatter ('% (asctime) s% (levelname) -8s:% (message) s ')# file LogFile_handler = logging. Filehandler ("Test.log")File_handler.setformatter (Formatter) # can specify output format by Setformatter# con
The logging Module Interface of python is similar to log4j. It is similar in concept and convenient to use. Logging. config. fileconfig () can be used to describe the log configuration in a file, which simplifies log initialization.
Routine:
# test.pyimport loggingimport logging.configlogging.config.fileConfig("logging.conf")#create loggerlogger = logging.getLogg
Four weeks five sessions (November 10)First, loggingLog is our key tool to troubleshoot problems, write log records, and when we have problems, you can quickly locate the code range to modify. Python gives us developers a good log module, let's introduce the logging module:First, let's look at an example:Import Logginglogging.debug (' This was debug message ') Logging.info (' This is Info message ') logging
parameters through SYS moduleImport Sysif __name__ = = "__main__":Print ("sys.argv[0]={0}". Format (Sys.argv[0]))Print ("Sys.argv[1]={1}". Format (Sys.argv[1]))2, Sys.stdout\stdin\stderrThe Stdout,stdin and stderr variables contain the stream object corresponding to the I/O stream3. Sys.stdout and PrintWhen we call print obj in Python, we actually call Sys.stdout.write (obj + "\ n"), print the required content to the console, and then append a newlin
Logging.basicconfig configuration logging to file A, and then using Logging.filehandler to generate records to file B loggerWhen using this logger log, both files A and B are logged simultaneously, and it feels like the mechanism is quite unexpected.#-*-Coding:utf8-*-import logginglogging.basicconfig ( level=logging. DEBUG, format= ' [% (asctime) s][% (process) d:% (thread) d][% (levelname) s
Logging.basicconfig (level=log_level, format='% (asctime) s% (filename) s[line:% (Lineno) d ]% (levelname) s% (message) s', datefmt='%a,%d%b%Y%h:%m:%s' , filename='parser_result.log', filemode= ' W ')logging.basicconfig function Parameters: FileName: Specifies the log file name FileMode: The same as the file function, specify the open mode of the log files,'W'Or'a'Format : Specifies the formats and contents of the output
less convenient, can be configured to use logging:Import logginglogging.basicconfig (FileName='/users/wenli.xu/desktop/log1.log', Level=logging.info)where filename indicates the log path, level indicates that only the severity is greater than or equal to info to be logged (the logging default is warning).The severity is lighter to heavy: debug,info,warning,error,criticalThe following methods can then be used to output critical information to the appr
Before using the logging module is just the internet casually searched a post, looked at the approximate method directly used. The problem now is that when you add a handler to a Logger object, you use Streamhandler in the configuration file, and you specify the output to stdout (the default is stderr). And since only one logger and one handler are used in the program, all log levels (INFO,DEBUG,ERROR, etc.) are redirected to a place that is standard
Code example for logging on to Tom via python and pythontom via emailIn many python tutorials, we will talk about examples of logging on to or sending emails. This article also provides an example. Log on to tom's mailbox and send a mail. The Code is as follows:
Def loginTom (username, password ):
Url1 = '''
Http:/
Python has a logging module to facilitate the recording of program action logs, this article is a simple example of the use of the logging module:
First introduce logging:
Import xlrdImport MySQLdbImport OSImport logging
First initialize the configuration in the main prog
This article mainly introduces the implementation code for logging on to the asp website page using python. For more information about how to log on to the asp website using python, see, the reason is that the asp page requires viewstate to be included in each request. Therefore, if you use python to log on, there is a
Python logging Best PracticesCause
I often joke with my colleagues. I said that in a company, I can clearly understand the log function. So I wrote an article to share some of my knowledge.The official Python article is the clearest among the log documents I have seen currently.
This flowchart is very important. I hope you can take a closer look.1. Applicable sce
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.