python-logging模块

log日志的概念

log日志是在程序中记录软件运行时所发生事件的方法。开发人员可以向他们的代码中调用日志记录相关的方法来表明发生了某些事情。一个事件可以用一个可包含可选变量数据的消息来描述。事件也有重要性的概念,这个重要性也可以被称为严重性级别(level)。

log的作用

  • 帮助我们进行程序调试
  • 了解程序运行情况,进而判断是否正常
  • 程序运行过程中的出现问题的分析和定位

logging模块

  是帮助我们简化操作文件的步骤,按照我们的要求规划日志等级,帮助我们规范格式

import logging

logging.debug('debug,msg')      # 最细节的,记录计算机计算细微细节
logging.info('info msg')        # 普通信息,记录用户的操作
logging.warning('warning msg')    # 警告信息 ,可能会影响到程序安全/正确的内容
logging.error('error msg')      # 错误信息 , 直接影响到程序的运行
logging.critical('critical msg')  # 危机,临界信息 , 直接把用户信息删除了

按照等级默认显示warning等级 以上信息

  1.上面列表中的日志等级是从上到下依次升高的,即:DEBUG < INFO < WARNING < ERROR < CRITICAL,而日志的信息量是依次减少的;

  2.logging模块指定日志记录器的日志级别,只有级别大于或等于该指定日志级别的日志记录才会被输出,小于该等级的日志记录将会被丢弃。

普通的日志输出

import logging

logging.debug('debug,msg') 
logging.info('info,msg') 
logging.warning('warning msg')    
logging.error('error msg')
logging.critical('critical msg') 
#这样写同上

logging.Debug('debug,msg') 
logging.Info('info,msg') 
logging.Warning('warning msg')    
logging.Error('error msg')
logging.Critical('critical msg') 


输出
ERROR:root:err msg WARNING:root:warning msg CRITICAL:root:critical msg

注意:发现并没有输出longging.Debug和logging.Info,这是因为logging模块提供的日志记录函数默认设置的日志级别是warning,因此只有warning级别的日志记录以及大于它的ERRORCRITICAL级别的日志记录被输出了,而小于它的DEBUGINFO级别的日志记录被丢弃了。

  • 打印出来的日志信息中各字段表示什么意思?

    上面输出结果中每行日志记录的各个字段含义分别是:

      日志级别:日志器名称:日志内容
  • 为什么会这样输出?

    因为logging模块提供的日志记录函数所使用的日志器设置的日志格式默认是BASIC_FORMAT,其值为:"%(levelname)s:%(name)s:%(message)s"

配置信息

  查看这些日志记录函数的实现代码,可以发现:当我们没有提供任何配置信息的时候,这些函数都会去调用logging.basicConfig(**kwargs)方法,且不会向该方法传递任何参数。继续查看basicConfig()方法的代码就可以找到上面这些问题的答案了。

怎么修改这些默认设置呢?

  我们调用上面这些日志记录函数之前,手动调用一下basicConfig()方法,把我们想设置的内容以参数的形式传递进去就可以了。

  1. 配置过的日志输出

import logging
logging.basicConfig(level =logging.DEBUG)
logging.debug('debug,msg')
logging.info('info msg')
logging.error('err msg')
logging.warning('warning msg')
logging.critical('critical msg')

输出:
DEBUG:root:debug,msg
INFO:root:info msg
ERROR:root:err msg
WARNING:root:warning msg
CRITICAL:root:critical msg
View Code

这样发现所有等级的日志都生效了,说明配置的结果生效了

       2.在配置日志器和日志级别的基础上,我们在配置下日志输出格式和输出目标文件

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',
                    filename = 'test.log',   #只能将日志信息写到文件中,无法在控制台显示
                    filemode = 'a')
logging.debug('debug message')   
logging.info('info message')     
logging.warning('warning message')
logging.error('error message')   
logging.critical('critical message') 

此时会发现控制台中已经没有输出日志内容了,但是在python代码文件的相同目录下会生成一个名为'my.log'的日志文件,该文件中的内容为:

Fri, 30 Nov 2018 01:08:03 day28��ϰ.py[line:73] DEBUG debug message
Fri, 30 Nov 2018 01:08:03 day28��ϰ.py[line:74] INFO info message
Fri, 30 Nov 2018 01:08:03 day28��ϰ.py[line:75] WARNING warning message
Fri, 30 Nov 2018 01:08:03 day28��ϰ.py[line:76] ERROR error message
Fri, 30 Nov 2018 01:08:03 day28��ϰ.py[line:77] CRITICAL critical message

还是发现两个问题:1.操作系统的编码可能会出现乱码问题
         2.不支持同时向文件和屏幕输出

使用logging四大组件记录日志

logger 对象的方式 :灵活性和可扩展性
logger = logging.getLogger  ()  #创建一个logger对象
logger.setLevel(logging.DEBUG)   #表示日志等级
#创建一个文件操作符,准备操作日志向文件写的事情
fh = logging.FileHandler('mylog.log',encoding='utf-8')
fh1 = logging.FileHandler('mylog1.log',encoding='utf-8')
#创建一个屏幕操作符,来准备操作日志向屏幕中写这件事情
sh = logging.StreamHandler()
#创建一个输出格式
formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
formatter2 = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
#组合
# 输出格式和文件操作符/屏幕操作符绑在一起
fh.setFormatter(formatter)
sh.setFormatter(formatter2)
sh.setLevel(logging.ERROR)
#logger对象分别和文件操作符/屏幕操作符绑在一起
logger.addHandler(fh)
logger.addHandler(fh1)
logger.addHandler(sh)
才开始能够使用logger来记录日志
mylog.log文件写入:
2018-11-30 01:44:11,259 log.py[line:92] DEBUG debug msg
2018-11-30 01:44:11,260 log.py.py[line:93] INFO info msg
2018-11-30 01:44:11,260  log.py.py[line:94] WARNING warning msg
2018-11-30 01:44:11,260  log.py.py[line:95] ERROR error msg
2018-11-30 01:44:11,261  log.py.py[line:96] CRITICAL critical msg

mylog1.log写入:
debug msg
info msg
warning msg
error msg
critical msg

 

 

 

...
posted @ 2018-11-30 01:20  FindSoul  阅读(195)  评论(0编辑  收藏  举报
var RENDERER = { POINT_INTERVAL : 5, FISH_COUNT : 3, MAX_INTERVAL_COUNT : 50, INIT_HEIGHT_RATE : 0.5, THRESHOLD : 50, init : function(){ this.setParameters(); this.reconstructMethods(); this.setup(); this.bindEvent(); this.render(); }, setParameters : function(){ this.$window = $(window); this.$container = $('#jsi-flying-fish-container'); this.$canvas = $('
'); this.context = this.$canvas.appendTo(this.$container).get(0).getContext('2d-disabled'); this.points = []; this.fishes = []; this.watchIds = []; }, createSurfacePoints : function(){ var count = Math.round(this.width / this.POINT_INTERVAL); this.pointInterval = this.width / (count - 1); this.points.push(new SURFACE_POINT(this, 0)); for(var i = 1; i < count; i++){ var point = new SURFACE_POINT(this, i * this.pointInterval), previous = this.points[i - 1]; point.setPreviousPoint(previous); previous.setNextPoint(point); this.points.push(point); } }, reconstructMethods : function(){ this.watchWindowSize = this.watchWindowSize.bind(this); this.jdugeToStopResize = this.jdugeToStopResize.bind(this); this.startEpicenter = this.startEpicenter.bind(this); this.moveEpicenter = this.moveEpicenter.bind(this); this.reverseVertical = this.reverseVertical.bind(this); this.render = this.render.bind(this); }, setup : function(){ this.points.length = 0; this.fishes.length = 0; this.watchIds.length = 0; this.intervalCount = this.MAX_INTERVAL_COUNT; this.width = this.$container.width(); this.height = this.$container.height(); this.fishCount = this.FISH_COUNT * this.width / 500 * this.height / 500; this.$canvas.attr({width : this.width, height : this.height}); this.reverse = false; this.fishes.push(new FISH(this)); this.createSurfacePoints(); }, watchWindowSize : function(){ this.clearTimer(); this.tmpWidth = this.$window.width(); this.tmpHeight = this.$window.height(); this.watchIds.push(setTimeout(this.jdugeToStopResize, this.WATCH_INTERVAL)); }, clearTimer : function(){ while(this.watchIds.length > 0){ clearTimeout(this.watchIds.pop()); } }, jdugeToStopResize : function(){ var width = this.$window.width(), height = this.$window.height(), stopped = (width == this.tmpWidth && height == this.tmpHeight); this.tmpWidth = width; this.tmpHeight = height; if(stopped){ this.setup(); } }, bindEvent : function(){ this.$window.on('resize', this.watchWindowSize); this.$container.on('mouseenter', this.startEpicenter); this.$container.on('mousemove', this.moveEpicenter); this.$container.on('click', this.reverseVertical); }, getAxis : function(event){ var offset = this.$container.offset(); return { x : event.clientX - offset.left + this.$window.scrollLeft(), y : event.clientY - offset.top + this.$window.scrollTop() }; }, startEpicenter : function(event){ this.axis = this.getAxis(event); }, moveEpicenter : function(event){ var axis = this.getAxis(event); if(!this.axis){ this.axis = axis; } this.generateEpicenter(axis.x, axis.y, axis.y - this.axis.y); this.axis = axis; }, generateEpicenter : function(x, y, velocity){ if(y < this.height / 2 - this.THRESHOLD || y > this.height / 2 + this.THRESHOLD){ return; } var index = Math.round(x / this.pointInterval); if(index < 0 || index >= this.points.length){ return; } this.points[index].interfere(y, velocity); }, reverseVertical : function(){ this.reverse = !this.reverse; for(var i = 0, count = this.fishes.length; i < count; i++){ this.fishes[i].reverseVertical(); } }, controlStatus : function(){ for(var i = 0, count = this.points.length; i < count; i++){ this.points[i].updateSelf(); } for(var i = 0, count = this.points.length; i < count; i++){ this.points[i].updateNeighbors(); } if(this.fishes.length < this.fishCount){ if(--this.intervalCount == 0){ this.intervalCount = this.MAX_INTERVAL_COUNT; this.fishes.push(new FISH(this)); } } }, render : function(){ requestAnimationFrame(this.render); this.controlStatus(); this.context.clearRect(0, 0, this.width, this.height); this.context.fillStyle = 'hsl(0, 0%, 95%)'; for(var i = 0, count = this.fishes.length; i < count; i++){ this.fishes[i].render(this.context); } this.context.save(); this.context.globalCompositeOperation = 'xor'; this.context.beginPath(); this.context.moveTo(0, this.reverse ? 0 : this.height); for(var i = 0, count = this.points.length; i < count; i++){ this.points[i].render(this.context); } this.context.lineTo(this.width, this.reverse ? 0 : this.height); this.context.closePath(); this.context.fill(); this.context.restore(); } }; var SURFACE_POINT = function(renderer, x){ this.renderer = renderer; this.x = x; this.init(); }; SURFACE_POINT.prototype = { SPRING_CONSTANT : 0.03, SPRING_FRICTION : 0.9, WAVE_SPREAD : 0.3, ACCELARATION_RATE : 0.01, init : function(){ this.initHeight = this.renderer.height * this.renderer.INIT_HEIGHT_RATE; this.height = this.initHeight; this.fy = 0; this.force = {previous : 0, next : 0}; }, setPreviousPoint : function(previous){ this.previous = previous; }, setNextPoint : function(next){ this.next = next; }, interfere : function(y, velocity){ this.fy = this.renderer.height * this.ACCELARATION_RATE * ((this.renderer.height - this.height - y) >= 0 ? -1 : 1) * Math.abs(velocity); }, updateSelf : function(){ this.fy += this.SPRING_CONSTANT * (this.initHeight - this.height); this.fy *= this.SPRING_FRICTION; this.height += this.fy; }, updateNeighbors : function(){ if(this.previous){ this.force.previous = this.WAVE_SPREAD * (this.height - this.previous.height); } if(this.next){ this.force.next = this.WAVE_SPREAD * (this.height - this.next.height); } }, render : function(context){ if(this.previous){ this.previous.height += this.force.previous; this.previous.fy += this.force.previous; } if(this.next){ this.next.height += this.force.next; this.next.fy += this.force.next; } context.lineTo(this.x, this.renderer.height - this.height); } }; var FISH = function(renderer){ this.renderer = renderer; this.init(); }; FISH.prototype = { GRAVITY : 0.4, init : function(){ this.direction = Math.random() < 0.5; this.x = this.direction ? (this.renderer.width + this.renderer.THRESHOLD) : -this.renderer.THRESHOLD; this.previousY = this.y; this.vx = this.getRandomValue(4, 10) * (this.direction ? -1 : 1); if(this.renderer.reverse){ this.y = this.getRandomValue(this.renderer.height * 1 / 10, this.renderer.height * 4 / 10); this.vy = this.getRandomValue(2, 5); this.ay = this.getRandomValue(0.05, 0.2); }else{ this.y = this.getRandomValue(this.renderer.height * 6 / 10, this.renderer.height * 9 / 10); this.vy = this.getRandomValue(-5, -2); this.ay = this.getRandomValue(-0.2, -0.05); } this.isOut = false; this.theta = 0; this.phi = 0; }, getRandomValue : function(min, max){ return min + (max - min) * Math.random(); }, reverseVertical : function(){ this.isOut = !this.isOut; this.ay *= -1; }, controlStatus : function(context){ this.previousY = this.y; this.x += this.vx; this.y += this.vy; this.vy += this.ay; if(this.renderer.reverse){ if(this.y > this.renderer.height * this.renderer.INIT_HEIGHT_RATE){ this.vy -= this.GRAVITY; this.isOut = true; }else{ if(this.isOut){ this.ay = this.getRandomValue(0.05, 0.2); } this.isOut = false; } }else{ if(this.y < this.renderer.height * this.renderer.INIT_HEIGHT_RATE){ this.vy += this.GRAVITY; this.isOut = true; }else{ if(this.isOut){ this.ay = this.getRandomValue(-0.2, -0.05); } this.isOut = false; } } if(!this.isOut){ this.theta += Math.PI / 20; this.theta %= Math.PI * 2; this.phi += Math.PI / 30; this.phi %= Math.PI * 2; } this.renderer.generateEpicenter(this.x + (this.direction ? -1 : 1) * this.renderer.THRESHOLD, this.y, this.y - this.previousY); if(this.vx > 0 && this.x > this.renderer.width + this.renderer.THRESHOLD || this.vx < 0 && this.x < -this.renderer.THRESHOLD){ this.init(); } }, render : function(context){ context.save(); context.translate(this.x, this.y); context.rotate(Math.PI + Math.atan2(this.vy, this.vx)); context.scale(1, this.direction ? 1 : -1); context.beginPath(); context.moveTo(-30, 0); context.bezierCurveTo(-20, 15, 15, 10, 40, 0); context.bezierCurveTo(15, -10, -20, -15, -30, 0); context.fill(); context.save(); context.translate(40, 0); context.scale(0.9 + 0.2 * Math.sin(this.theta), 1); context.beginPath(); context.moveTo(0, 0); context.quadraticCurveTo(5, 10, 20, 8); context.quadraticCurveTo(12, 5, 10, 0); context.quadraticCurveTo(12, -5, 20, -8); context.quadraticCurveTo(5, -10, 0, 0); context.fill(); context.restore(); context.save(); context.translate(-3, 0); context.rotate((Math.PI / 3 + Math.PI / 10 * Math.sin(this.phi)) * (this.renderer.reverse ? -1 : 1)); context.beginPath(); if(this.renderer.reverse){ context.moveTo(5, 0); context.bezierCurveTo(10, 10, 10, 30, 0, 40); context.bezierCurveTo(-12, 25, -8, 10, 0, 0); }else{ context.moveTo(-5, 0); context.bezierCurveTo(-10, -10, -10, -30, 0, -40); context.bezierCurveTo(12, -25, 8, -10, 0, 0); } context.closePath(); context.fill(); context.restore(); context.restore(); this.controlStatus(context); } }; $(function(){ RENDERER.init(); });