1. 例子

import logging
logging.basicConfig(filename='log.txt', #文件名
level=logging.DEBUG, #级别
format=u'时间:%(asctime)s\n级别:%(levelname)s\n消息:%(message)s\n', #日志格式
datefmt='%Y-%m-%d %H:%M:%S') # 时间格式
logging.debug(u'第一条记录')
logging.info(u'第二条记录')

2. 级别

日志所记录的消息可以划分为不同的级别,一般用以下几种预定义的级别。

每种级别有对应的值,可以用来比较级别的高低。

级别
CRITICAL 50
ERROR 40
WARNING 30
INFO 20
DEBUG 10
NOTSET 0

每个级别都有对应的方法,用小写字母,比如 logging.debug() , logging.info(),分别用来记录 DEBUG 级别和 INFO 级别的消息。

logging.basicConfig 中配置的级别可以用来过滤消息,比配置级别低的消息将被忽略,不会写入文件。

比如,如果一开始配置的是 level=logging.INFO ,那么调用 logging.debug() 处理的消息将被忽略,不会记录到文件。只有用 info() 或者 warning() 以及更高级别才会被记录。

3. 日志格式

格式化字符串支持如下参数:

参数 解释
%(asctime)s Human-readable time when the LogRecord was created. By default this is of the form '2003-07-08 16:49:45,896'.
%(created)f Time when the LogRecord was created (as returned by time.time()).
%(filename)s Filename portion of pathname.
%(funcName)s Name of function containing the logging call.
%(levelname)s Text logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').
%(levelno)s Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL).
%(lineno)d Source line number where the logging call was issued (if available).
%(module)s Module (name portion of filename).
%(msecs)d Millisecond portion of the time when the LogRecord was created.
%(message)s The logged message.
%(name)s Name of the logger used to log the call.
%(pathname)s Full pathname of the source file where the logging call was issued (if available).
%(process)d Process ID (if available).
%(processName)s Process name (if available).
%(relativeCreated)d Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.
%(thread)d Thread ID (if available).
%(threadName)s Thread name (if available).

3. 时间格式

时间格式化字符串与time.strftime()使用相同的参数

参数 解释
%a Locale's abbreviated weekday name.
%A Locale's full weekday name.
%b Locale's abbreviated month name.
%B Locale's full month name.
%c Locale's appropriate date and time representation.
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%I Hour (12-hour clock) as a decimal number [01,12].
%j Day of the year as a decimal number [001,366].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%p Locale's equivalent of either AM or PM.
%S Second as a decimal number [00,61].
%U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
%w Weekday as a decimal number [0(Sunday),6].
%W Week number of the year (Monday as the first day of the week) as a decimal number [00,53].
%x Locale's appropriate date representation.
%X Locale's appropriate time representation.
%y Year without century as a decimal number [00,99].
%Y Year with century as a decimal number.
%Z Time zone name (no characters if no time zone exists).
%% A literal '%' character.

4. 另一种写法

麻烦一点,但是可以定制多个logger

import logging

logger = logging.getLogger(u'mylogger')
handler = logging.FileHandler(u'log1.txt')
formatter = logging.Formatter(u'时间:%(asctime)s\n级别:%(levelname)s\n消息:%(message)s\n')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
logger.debug(u'第一条记录')
logger.info(u'第二条记录') logger2 = logging.getLogger(u'mylogger2')
handler2 = logging.FileHandler(u'log2.txt')
formatter2 = logging.Formatter(u'时间:%(asctime)s\n级别:%(levelname)s\n消息:%(message)s\n')
handler2.setFormatter(formatter2)
logger2.addHandler(handler2)
logger2.setLevel(logging.DEBUG)
logger2.debug(u'第一条记录')
logger2.info(u'第二条记录')

logging 文件日志的更多相关文章

  1. .NET跨平台之旅:增加文件日志功能遇到的挫折

    在将我们的ASP.NET 5示例站点(about.cnblogs.com)升级至ASP.NET 5 RC1的时候,我们增加了控制台日志功能. 在ASP.NET 5添加日志功能很简单,只需在projec ...

  2. 解决logging模块日志信息重复问题

    解决logging模块日志信息重复问题 问题描述 相信大家都知道python的logging模块记录日志信息的步骤: # coding:utf-8 import logging ### 创建logge ...

  3. logging模板日志格式

    logging模板日志格式 创建loginfo.py模块,然后导入定义的logging配置,即可使用 cat loginfo.py """ logging配置 " ...

  4. Python学习笔记:logging(日志处理)

    在一个软件中,日志是可以说必不可少的一个组成部分,通常会在定位客户问题或者记录软件使用情况等场景中会用到.logging模板块是Python的一个内置标准库,用于实现对日志的控制输出,对于平常的日志输 ...

  5. 【java】java自带的java.util.logging.Logger日志功能

    偶然翻阅到一篇文章,注意到Java自带的Logger日志功能,特地来细细的看一看,记录一下. 1.Java自带的日志功能,默认的配置 ①Logger的默认配置,位置在JRE安装目录下lib中的logg ...

  6. 分享 NET 5.x 自定义文件日志实现 原汁原味

    下面直接贴出实现代码 FileLoggerProvider /// <summary> /// 文件记录器提供商 /// </summary> public class Fil ...

  7. Spring 使用 SLF4J代替 Commons Logging 写日志 异常

    项目的日志更换成slf4j和logback后,发现项目无法启动.错误提示 Caused by: java.lang.NoClassDefFoundError: Lorg/apache/commons/ ...

  8. php 文件日志类

    php文件日志类,按年月日组织目录结构. <?php class FileLog { private $_filepath; //文件路径 private $_filename; //日志文件名 ...

  9. 【分享】我们用了不到200行代码实现的文件日志系统,极佳的IO性能和高并发支持,附压力测试数据

    很多项目都配置了日志记录的功能,但是,却只有很少的项目组会经常去看日志.原因就是日志文件生成规则设置不合理,将严重的错误日志跟普通的错误日志混在一起,分析起来很麻烦. 其实,我们想要的一个日志系统核心 ...

随机推荐

  1. chrome中不可见字符引发的float问题

    起因是刷知乎时碰到这么个问题:https://www.zhihu.com/question/41400503 问题代码如下: <!DOCTYPE html> <html lang=& ...

  2. 使用Proj库进行大地坐标转空间坐标、投影坐标的一个示例

    最近研究了proj库的使用,自己写了一个小demo,仅供参考. void demoPROJ() { const char* wgs84 = "+proj=tmerc +ellps=WGS84 ...

  3. [LeetCode] Inorder Successor in BST 二叉搜索树中的中序后继节点

    Given a binary search tree and a node in it, find the in-order successor of that node in the BST. No ...

  4. [LeetCode] Invert Binary Tree 翻转二叉树

    Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to 4 / \ 7 2 / \ / \ 9 6 3 1 Trivia: This problem wa ...

  5. [LeetCode] Read N Characters Given Read4 用Read4来读取N个字符

    The API: int read4(char *buf) reads 4 characters at a time from a file.The return value is the actua ...

  6. matplotlib 高级用法实例--共享x轴

    http://localhost:8888/notebooks/duanqs/matplotlib_advanced_example.ipynb 我不会弄呀, 刚才从matplotlib文档里吧示例用 ...

  7. 【MySQL】mysql workbench

    1.导入,导出,数据之间的传输[两台服务器]2.连接管理3.服务器管理4.表的管理

  8. 【WPF】释放图像资源, [删除时报另一进程占用]

    源:zhantianyou CODE private BitmapImage ReturnBitmap(string destFile) { // Read byte[] from png file ...

  9. html javascript css3 php3.2.3离线手册

    各位新年快乐! 愿大家"愿有前程可奔赴,也有岁月可回头"! 发现个离线手册很全的网站,分享大家,也mark自用. http://www.shouce.ren/ 手册网

  10. 我用ANDROID STUDIO开发,页面上总包这个警告,很烦!网上说是sdk版本问题,但是我是基于25开发的,最小版本也是19,有没有老司机啊?3克油