日志处理是项目的必备功能,配置合理的日志,可以帮助我们了解系统的运行状况、定位位置,辅助数据分析技术,还可以挖掘出一些额外的系统信息。

本文介绍Python内置的日志处理模块logging的常见用法。

1,日志等级

日志是分等级的,这点不难理解,任何信息都有轻重缓急之分,通过分级,我们可以方便的对日志进行刷选过滤,提高分析效率。

简单说,日志有以下等级:

DEBUG,INFO,WARNING,ERROR,CRITICAL

其重要性依次增强。一般的,这五个等级就足够我们日常使用了。

2,日志格式

日志本质上记录某一事件的发生,那么它应当包括但不限于以下信息:

事件等级,发生时间,地点(代码位置),错误信息

3,logging模块的四大组件

通过这四大组件,我们便可以自由配置自己的日志格式。

4,案例展示

在实际应用中,一般会按照时间或者预置的大小对日志进行定期备份和分割,我们下面就按照这两点分别进行介绍:

4-1,按照预置的文件大小配置日志,并自动分割备份

代码:

 #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import logging.handlers
import os def get_logger():
log_path = "./logs" if not os.path.isdir(log_path):
os.mkdir(log_path)
os.chmod(log_path, 0777) all_log = log_path + os.path.sep + "all.log"
error_log = log_path + os.path.sep + "error.log" if not os.path.isfile(all_log):
os.mknod(all_log)
os.chmod(all_log, 0777) if not os.path.isfile(error_log):
os.mknod(error_log)
os.chmod(error_log, 0777) log_format = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") # get logger object
my_logger = logging.getLogger("my_logger")
my_logger.setLevel(logging.DEBUG) # auto split log file by interval specified(every minute), record debug message and above.
rf_handler = logging.handlers.TimedRotatingFileHandler(all_log, when='M', interval=1, backupCount=3)
rf_handler.setLevel(logging.DEBUG)
rf_handler.setFormatter(log_format) # don't split log file, only record error message and above.
f_handler = logging.FileHandler(error_log)
f_handler.setLevel(logging.ERROR)
f_handler.setFormatter(log_format) my_logger.addHandler(rf_handler)
my_logger.addHandler(f_handler) return my_logger def test():
msg = {"debug": "This is a debug log",
"info": "This is a info log",
"warning": "This is a warning log",
"error": "This is a error log",
"critical": "This is a critical log"} for k, v in msg.items():
if k == "debug":
logger.debug(v)
elif k == "info":
logger.info(v)
elif k == "warning":
logger.warning(v)
elif k == "error":
logger.error(v)
elif k == "critical":
logger.critical(v) if __name__ == '__main__':
index = 1
logger = get_logger() while True:
test()
print(index)
index = index + 1

实际效果:

all.log保存最新的日志,历史副本按照时间后缀进行保存,最多留存三个。

4-2,按照预置的文件大小配置日志,并自动分割备份

代码:

 #!/usr/bin/env python
# -*- coding: utf-8 -*- import logging
from logging.handlers import RotatingFileHandler import os def test():
msg = {"debug": "This is a debug log",
"info": "This is a info log",
"warning": "This is a warning log",
"error": "This is a error log",
"critical": "This is a critical log"} for k, v in msg.items():
if k == "debug":
logger.debug(v)
elif k == "info":
logger.info(v)
elif k == "warning":
logger.warning(v)
elif k == "error":
logger.error(v)
elif k == "critical":
logger.critical(v) def get_logger():
dir_path = "./logs"
file_name = "rotating_log"
if not os.path.isdir(dir_path):
os.mkdir(dir_path)
os.chmod(dir_path, 0777) file_path = dir_path + "/" + file_name
if not os.path.isfile(file_path):
os.mknod(file_path)
os.chmod(file_path, 0777) my_logger = logging.getLogger("rotating_log")
my_logger.setLevel(level=logging.INFO) # auto split log file at max size of 4MB
r_handler = RotatingFileHandler(file_path, maxBytes=4*1024*1024, backupCount=3)
r_handler.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
r_handler.setFormatter(formatter) my_logger.addHandler(r_handler) return my_logger if __name__ == '__main__':
logger = get_logger()
index = 1
while True:
test()
print(index)
index = index + 1

最终效果:

Python日志模块logging简介的更多相关文章

  1. python日志模块logging

    python日志模块logging   1. 基础用法 python提供了一个标准的日志接口,就是logging模块.日志级别有DEBUG.INFO.WARNING.ERROR.CRITICAL五种( ...

  2. 【python】【logging】python日志模块logging常用功能

    logging模块:应用程序的灵活事件日志系统,可以打印并自定义日志内容 logging.getLogger 创建一个log对象 >>> log1=logging.getLogger ...

  3. Python 日志模块logging

    logging模块: logging是一个日志记录模块,可以记录我们日常的操作. logging日志文件写入默认是gbk编码格式的,所以在查看时需要使用gbk的解码方式打开. logging日志等级: ...

  4. Python日志模块logging用法

    1.日志级别 日志一共分成5个等级,从低到高分别是:DEBUG INFO WARNING ERROR CRITICAL. DEBUG:详细的信息,通常只出现在诊断问题上 INFO:确认一切按预期运行 ...

  5. python日志模块logging学习

    介绍 Python本身带有logging模块,其默认支持直接输出到控制台(屏幕),或者通过配置输出到文件中.同时支持TCP.HTTP.GET/POST.SMTP.Socket等协议,将日志信息发送到网 ...

  6. Python 日志模块 logging通过配置文件方式使用

    vim logger_config.ini[loggers]keys=root,infoLogger,errorlogger [logger_root]level=DEBUGhandlers=info ...

  7. Python日志模块logging&JSON

    日志模块的用法 json部分 先开一段测试代码:注意  str可以直接处理字典   eval可以直接将字符串转成字典的形式 dic={'key1':'value1','key2':'value2'} ...

  8. 『无为则无心』Python日志 — 64、Python日志模块logging介绍

    目录 1.日志的作用 2.为什么需要写日志 3.Python中的日志处理 (1)logging模块介绍 (2)logging模块的四大组件 (3)logging日志级别 1.日志的作用 从事与软件相关 ...

  9. python日志模块---logging

    1.将日志打印到屏幕 import logging logging.debug('This is debug message---by liu-ke') logging.info('This is i ...

随机推荐

  1. Cocos2d-x 学习笔记(11.1) MoveBy MoveTo

    1. MoveBy MoveTo 两方法都是对node的平移,MoveBy是相对当前位置的移动.MoveTo是By的子类,是移动到世界坐标位置. 1.1 成员变量和create方法 MoveBy的主要 ...

  2. F#周报2019年第43期

    新闻 F# eXchange 2020--征文通知 FSSF在忙什么?2019年第三季度版本 Miguel强烈推荐使用TensorFlow.NET 运行在ASP.NET Core 3上的SAFE-Bo ...

  3. PHP使用RabbitMQ消息队列

    1.安装amqp拓展 安装流程 2.下载工具包 php-amqplib  composer require php-amqplib/php-amqplib   3.代码操作如下 [消费消息] < ...

  4. 百万年薪python之路 -- 请求跨域和CORS协议详解

    楔子 什么是同源策略 同源策略,它是由Netscape提出的一个著名的安全策略.现在所有支持JavaScript 的浏览器都会使用这个策略.所谓同源是指,域名,协议,端口相同.当一个浏览器的两个tab ...

  5. java面试官:兄弟简单谈谈Static、final、Static final各种用法吧

    前言 对Static.final.Static final这几个关键词熟悉又陌生?想说却又不知怎么准确说出口?好的,本篇博客文章将简短概要出他们之间的各自的使用,希望各位要是被你的面试官问到了,也能从 ...

  6. 追查Could not get a databaseId from dataSource

    Mybatis 创建连接池的时候报错: ERROR 2017-03-15 00:44:50,333 commons.JakartaCommonsLoggingImpl:38 Could not get ...

  7. Leetcode Tags(4)Stack & Queue

    一.232. Implement Queue using Stacks private Stack<Integer> stack; /** Initialize your data str ...

  8. Mysql数据库(三)Mysql表结构管理

    一.MySQL数据类型 1.数字类型 (1)整数数据类型包括TINYINT/BIT/BOOL/SMALLINT/MEDIUMINT/INT/BIGINT (2)浮点数据类型包括FLOAT/DOUBLE ...

  9. Python+Keras+TensorFlow车牌识别

    这个是我使用的车牌识别开源项目的地址:https://github.com/zeusees/HyperLPR Python 依赖 Anaconda for Python 3.x on Win64 Ke ...

  10. SpringBoot2.X整合Actuator

    一 说明 Actuator 的定义 actuator 是一个制造术语,指的是用于移动或控制某物的机械装置.执行器可以通过一个小的变化产生大量的运动. 要将 actuator 添加到基于 Maven 的 ...