python日志简单用法

python内置了日志系统,但是很多时候写代码的时候都图简单。将这个事情忽略了。这里记录一个实例来说说明

import logging

logging.basicConfig(level=logging.DEBUG,
        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
        datefmt='%a, %d %b %Y %H:%M:%S')

时间相关的format:

DirectiveMeaning
%aLocale’s abbreviated weekday name.
%ALocale’s full weekday name.
%bLocale’s abbreviated month name.
%BLocale’s full month name.
%cLocale’s appropriate date and time representation.
%dDay of the month as a decimal number [01,31].
%HHour (24-hour clock) as a decimal number [00,23].
%IHour (12-hour clock) as a decimal number [01,12].
%jDay of the year as a decimal number [001,366].
%mMonth as a decimal number [01,12].
%MMinute as a decimal number [00,59].
%pLocale’s equivalent of either AM or PM. (1)
%SSecond as a decimal number [00,61]. (2)
%UWeek number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. (3)
%wWeekday as a decimal number [0(Sunday),6].
%WWeek number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. (3)
%xLocale’s appropriate date representation.
%XLocale’s appropriate time representation.
%yYear without century as a decimal number [00,99].
%YYear with century as a decimal number.
%ZTime zone name (no characters if no time zone exists).
%%A literal ‘%’ character.
FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
logging.basicConfig(format=FORMAT)
d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
logger = logging.getLogger('tcpserver')
logger.warning('Protocol problem: %s', 'connection reset', extra=d)

2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset

这个官方实例比较好玩,就是将开发者的扩展的信息打印进去了。这个里面会将ip用户名都输出到里面了。

fh = logging.FileHandler('test.log')
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)

创建自定义的handler对象,可以是文件流,或者是console流。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值