python如何写日志_【Python】教你如何在python中添加日志
背景
起因是這次的項目用thrift來連接算法(python)和業務邏輯(java),因此有必要在python中添加日志來記錄傳入的參數。這樣,當算法端沒有正確響應時,就能方便地排查原因。
簡易版實現
首先,我在google里面找到了官方的HOWTO文檔資料。具體文檔見參考資料1.
如何將日志落成日志文件?
import logging
?
logging.basicConfig(filename='example.log', level=logging.DEBUG)
logging.debug('this message should go to the log file')
logging.info('so should this')
logging.warning('and this, too')
運行上面的代碼,在本地就會出現example.log的文件了。看起來很簡單,但是需要進一步了解如何在項目中使用。
進階版實現
知識點
然后我在medium上找到了一篇博客來看。博客中提到,配置日志只需要三個零件:一個logger對象——官方的logger工具
一個formatter——告訴logger要輸出成什么樣的格式
一個handler——設置logger輸出到文件還是打印到控制臺
代碼實現
我想實現的功能很簡單,每次調用print_name(name)函數時,都會把傳入的參數name記錄到日志里。
依照這篇博客,我寫了兩個.py文件:一個用來存放對logger的配置,
另一個用來實現功能模塊,并在該模塊中調用logger,實現記錄日志的功能。
第一個文件名為logging_config.py, 內容如下:
import logging
class Config():
# creating a logger對象
logger = logging.getLogger('mylogger')
# define the default level of the logger
logger.setLevel(logging.INFO)
# creating a formatter
formatter = logging.Formatter( '%(asctime)s|%(levelname)s->%(message)s' )
# creating a handler to log on the filesystem
file_handler=logging.FileHandler('mylogfile.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.INFO)
# adding handlers to our logger
logger.addHandler(file_handler)
#logger.info('this is a log message...')
def get_config(self):
return self.logger
第二個文件名為test_module.py, 內容如下:
import logging_config
?
logger = logging_config.Config().get_config()
?
def print_name(name):
logger.info(name)
print(name)
接下來,在console里進行如下操作:
import test_moduletest_module.print_name('Nicole')
test_module.print_name('Duoduo')test_module.print_name('Dabao')
在控制臺會相應地打印這三個名字。 打開這兩個文件所在的文件夾,會發現多了一個mylogfile.log的文件,用記事本打開,里面的內容為:日志內容
參考資料
總結
以上是生活随笔為你收集整理的python如何写日志_【Python】教你如何在python中添加日志的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 项目服务路由保存不成功_汽车延保服务有哪
- 下一篇: mybatis 自定义函数_JDK动态代