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

本文介绍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. WCE-hash注入工具使用

    wce的使用说明如下 参数解释:-l          列出登录的会话和NTLM凭据(默认值)-s               修改当前登录会话的NTLM凭据 参数:<用户名>:<域 ...

  2. [Luogu1379]八数码难题

    题目描述 在3×3的棋盘上,摆有八个棋子,每个棋子上标有1至8的某一数字.棋盘中留有一个空格,空格用0来表示.空格周围的棋子可以移到空格中.要求解的问题是:给出一种初始布局(初始状态)和目标布局(为了 ...

  3. PowerShell渗透--Empire(二)

    权限提升 Bypass UAC usemodule powershell/privesc/bypassuac 设置listener execute list查看 usemodule powershel ...

  4. Smali语言基础语法

    1.Smali语言基础语法-数据类型与描述符 smali中有两类数据类型:基本类型和引用类型.引用类型是指数组和对象,其它都是基础类型. 基本类型以及每种类型的描述符: Java类型 类型描述符 说明 ...

  5. Mysql数据库(二)Mysql数据库管理

    一 .创建数据库 1.通过CREATE DATABASE db_library;创建名称为db_library的数据库. 2.通过CREATE SCHEMA db_library1;创建名称为db_l ...

  6. spring cloud 2.x版本 Ribbon服务发现教程(内含集成Hystrix熔断机制)

    本文采用Spring cloud本文为2.1.8RELEASE,version=Greenwich.SR3 前言 本文基于前两篇文章eureka-server和eureka-client的实现. 参考 ...

  7. activeMQ 安装及启动异常处理

    一.环境: [root@centos_6 ~]# cat /etc/system-release CentOS release 6.5 (Final) [root@centos_6 ~]# uname ...

  8. CVE-2019-17671:Wordpress未授权访问漏洞复现

    0x00 简介 WordPress是一款个人博客系统,并逐步演化成一款内容管理系统软件,它是使用PHP语言和MySQL数据库开发的,用户可以在支持 PHP 和 MySQL数据库的服务器上使用自己的博客 ...

  9. python正则小结

    注意pattern字符串前要加r    原始字符串 元字符 .                匹配除换行的任意字符 ^            匹配开头 $            匹配结尾 表示重复   ...

  10. [专题总结]矩阵树定理Matrix_Tree及题目&题解

    专题做完了还是要说两句留下什么东西的. 矩阵树定理通俗点讲就是: 建立矩阵A[i][j]=edge(i,j),(i!=j).即矩阵这一项的系数是两点间直接相连的边数. 而A[i][i]=deg(i). ...