Python輸出日誌

jieforest發表於2012-08-06
Python provides a very powerful logging library in its standard library. A lot of programmers use print statements for debugging (myself included), but you can also use logging to do this. It’s actually cleaner to use logging as you won’t have to go through all your code to remove the print statements. In this tutorial we’ll cover the following topics:

•        Creating a simple logger

•        How to log from multiple modules

•        Log formatting

•        Log configuration

By the end of this tutorial, you should be able to confidently create your own logs for your applications. Let’s get started!

Creating a Simple Logger

Creating a log with the logging module is easy and straight-forward. It’s easiest to just look at a piece of code and then explain it, so here’s some code for you to read:

CODE:

import logging

# add filemode="w" to overwrite
logging.basicConfig(filename="sample.log", level=logging.INFO)

logging.debug("This is a debug message")
logging.info("Informational message")
logging.error("An error has happened!")

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/301743/viewspace-739941/,如需轉載,請註明出處,否則將追究法律責任。

相關文章