A class for global logging
Some time we need to record the logging information in multiple module, however if we use the follows logging configuration would lead the log cannot write to the same file for the file stream would be lock in multiple process.
import logging
#setting the the logging configuration
logging.basicConfig(level=logging.DEBUG,
filename='/home/ronglian/project/ebscn/log/fastlogin.log',
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filemode='w')
The follows logging class would avoid the multiple process problem.
import logging
#from cloghandler import ConcurrentRotatingFileHandler class NullHandler(logging.Handler):
def emit(self,record):
pass
class GlobalLogging:
log = None
@staticmethod
#def getInstance():
def getLog():
if GlobalLogging.log == None:
GlobalLogging.log = GlobalLogging()
return GlobalLogging.log def __init__(self):
self.logger = None
self.handler = None
self.level = logging.DEBUG
self.logger = logging.getLogger("GlobalLogging")
self.formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
h = NullHandler()
self.logger.addHandler(h)
self.logger.setLevel(self.level) #fixme
self.setLoggingToFile("/home/ronglian/project/taskschedule/logs/taskschedule.log") def setLoggingToFile(self,file):
#fh = ConcurrentRotatingFileHandler(file,"a", 512*1024, 5)
fh = logging.FileHandler(file)
fh.setFormatter(self.formatter)
self.logger.addHandler(fh) def setLoggingToConsole(self) :
ch = logging.StreamHandler()
ch.setFormatter(self.formatter)
self.logger.addHandler(ch) def setLoggingToHandler(self,handler):
self.handler = handler def setLoggingLevel(self,level):
self.level = level
self.logger.setLevel(level) def debug(self,s):
self.logger.debug(s)
if not self.handler == None and self.level <= logging.DEBUG :
self.handler('-DEBUG-:' + s)
def info(self,s): self.logger.info(s)
if not self.handler == None and self.level <= logging.INFO:
self.handler('-INFO-:' + s)
def warn(self,s):
self.logger.warn(s)
if not self.handler == None and self.level <= logging.WARNING:
self.handler('-WARN-:' + s)
def error(self,s): self.logger.error(s)
if not self.handler == None and self.level <= logging.ERROR:
print 'enter error'
self.handler('-ERROR-:' + s)
def critical(self,s):
self.logger.critical(s)
if not self.handler == None and self.level <= logging.CRITICAL:
self.handler('-CRITICAL-:' + s)
Sometimes, we need to generate the logs depend on the different time frequency, so we can use the rotate handler, such as the follows:
import logging
import datetime
from logging.handlers import TimedRotatingFileHandler
from logging.handlers import RotatingFileHandler
#from cloghandler import ConcurrentRotatingFileHandler
'''
CRITICAL 50,ERROR 40,WARNING 30,INFO 20,DEBUG 10,NOTSET 0
'''
import os
import sys
Basedir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) class NullHandler(logging.Handler): def emit(self, record):
pass class GlobalLogging:
log = None @staticmethod
# def getInstance():
def getLog():
if GlobalLogging.log == None:
GlobalLogging.log = GlobalLogging()
return GlobalLogging.log def __init__(self):
self.logger = None
self.handler = None
self.level = logging.INFO
self.logger = logging.getLogger("GlobalLogging")
self.formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") self.logger.setLevel(self.level) # fixme
date = datetime.datetime.now().strftime("%Y-%m-%d-%M")
fname = str(Basedir) + '/logs/taskschedule.log'
# if not os.path.exists(fname+'.'+date):
# os.mknod(fname)
# os.system('chmod 777 ' + fname)
h = TimedRotatingFileHandler(fname,
when="midnight",
interval=1,
backupCount=100)
# h= RotatingFileHandler(fname,
# mode='a',
# backupCount=20)
h.setFormatter(self.formatter)
self.logger.addHandler(h)
# print fname #self.setLoggingToFile(fname) def setLoggingToFile(self, file):
#fh = ConcurrentRotatingFileHandler(file,"a", 512*1024, 5)
fh = logging.FileHandler(file)
fh.setFormatter(self.formatter)
self.logger.addHandler(fh) def setLoggingToConsole(self):
ch = logging.StreamHandler()
ch.setFormatter(self.formatter)
self.logger.addHandler(ch) def setLoggingToHandler(self, handler):
self.handler = handler def setLoggingLevel(self, level):
self.level = level
self.logger.setLevel(level) def debug(self, s):
self.logger.debug(s)
if not self.handler == None and self.level <= logging.DEBUG:
self.handler('-DEBUG-:' + s) def info(self, s): self.logger.info(s)
print self.handler,self.level
if not self.handler == None and self.level <= logging.INFO:
self.handler('-INFO-:' + s) def warn(self, s):
self.logger.warn(s)
if not self.handler == None and self.level <= logging.WARNING:
self.handler('-WARN-:' + s) def error(self, s): self.logger.error(s)
if not self.handler == None and self.level <= logging.ERROR:
print 'enter error'
self.handler('-ERROR-:' + s) def critical(self, s):
self.logger.critical(s)
if not self.handler == None and self.level <= logging.CRITICAL:
self.handler('-CRITICAL-:' + s)
A class for global logging的更多相关文章
- Java Se: Logging 框架说明
Java Logging 用惯了log4j等日志工具,竟然不知Java还自带了个log工具.今天有空了就来了解一下. 先来看一个简单的例子: public class SystemTest { pri ...
- Java日志工具之java.util.logging.Logger
今天总结下JDK自带的日志工具Logger,虽然它一直默默无闻,但有时使用它却比较方便.更详细的信息可以查看JDK API手册,本文只是简单示例入门. 创建Logger 我们可以使用Logger的工厂 ...
- Java数据持久层框架 MyBatis之API学习十(Logging详解)
对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...
- java.util.logging
我们目前记录日志用的最多的就是Apache的log4j,其实java.util本身也提供日志记录功能,即java.util.logging,值得关注的就是它的等级与log4j的等级有所不同: 首先我们 ...
- 【java】java自带的java.util.logging.Logger日志功能
偶然翻阅到一篇文章,注意到Java自带的Logger日志功能,特地来细细的看一看,记录一下. 1.Java自带的日志功能,默认的配置 ①Logger的默认配置,位置在JRE安装目录下lib中的logg ...
- MyBatis基础入门--知识点总结
对原生态jdbc程序的问题总结 下面是一个传统的jdbc连接oracle数据库的标准代码: public static void main(String[] args) throws Exceptio ...
- MyBatis日志配置
关于MyBatis的日志,其实MyBatis已经弄得很好了,你甚至都不用配置,只要导入了jar包,MyBatis就会自动寻找. 具体步骤 1.导入jar包,就是把下载MyBatis时,lib里的包复制 ...
- java 持久框架mybatis的初步学习
什么是 MyBatis? MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架.MyBatis 消除 了几乎所有的 JDBC 代码和参数的手工设置以及结果集的检索.MyBati ...
- MyBatis入门基础(一)
一:对原生态JDBC问题的总结 新项目要使用mybatis作为持久层框架,由于本人之前一直使用的Hibernate,对mybatis的用法实在欠缺,最近几天计划把mybatis学习一哈,特将学习笔记记 ...
随机推荐
- 机器学习实战 - 读书笔记(07) - 利用AdaBoost元算法提高分类性能
前言 最近在看Peter Harrington写的"机器学习实战",这是我的学习笔记,这次是第7章 - 利用AdaBoost元算法提高分类性能. 核心思想 在使用某个特定的算法是, ...
- ahjesus SSHkey登陆linux服务器,无需密码,ubuntu
cd ~/.ssh/如果目录不存在就新建一个 mkdir ~/.ssh 制作公匙 ssh-keygen -t rsa默认会生成id_rsa.pub的公匙 将公匙推送到指定的服务器 scp id_rsa ...
- AngularJs Cookie 的使用
最新在学习 AngularJs ,发现网上很难搜到 AngularJs.Cookie 教程, 就自己写篇博客,希望能帮到刚学的人. 废话不多说上代码 首先要引用 angular-cookies.js ...
- Vue混合
gitHub地址: https://github.com/lily1010/vue_learn/tree/master/lesson13 一 定位 混合以一种灵活的方式为组件提供分布复用功能.混合对象 ...
- MSCRM 2015 新功能(一)
MS官网信息:http://www.microsoft.com/en-us/dynamics/crm-customer-center/what-s-new.aspx MS官网中提到的新功能主要以下几块 ...
- iOS远程推送之友盟Push
更新记录: 1.2015年10月23日上午10:10分更新,优化了该类,去除了不必要的方法. ----------------------------------------------------- ...
- App开发流程之状态栏和导航栏
记录状态栏和导航栏的设置和控制,统一在基类视图控制器中完成. 状态栏. 状态栏高度为20,iOS7以后背景完全透明. 样式枚举如下: typedef NS_ENUM(NSInteger, UIStat ...
- 基础学习day04---数组的操作
一.数组基本常见操作 1.1.静态初始化 //第一种声明 //第一种声明 int [] arr=new int[5]; //第二种声明 int [] arr1=new int[]{5,3,8,1,9, ...
- iOS-申请测试证书详解(多图原创)
申请测试证书详解 前言 App开发和发布过程中证书基础知识:1. Certification(证书)证书是对电脑开发资格的认证,每个开发者帐号有一套,分为两种:1) Developer Certifi ...
- linux命令----网络地址
IP即时生效(重启后失效): ifconfig eth0 192.168.1.102 netmask 255.255.255.0 route add default gw 192.168.1.1 ...