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学习一哈,特将学习笔记记 ...
随机推荐
- 引入js和css文件的总结
1.用script标签引入javascript时,浏览器对于javascript的加载某些是并行的,某些是串行的,如IE8,Chorme2和firefox3都是串行加载的. 2.charset编码也就 ...
- HDU 1028(母函数)
Online Judge Online Exercise Online Teaching Online Contests Exercise Author F.A.QHand In HandOnline ...
- 【转载】NodeJS、NPM安装配置步骤(windows版本)
1.windows下的NodeJS安装是比较方便的(v0.6.0版本之后,支持windows native),只需要登陆官网(http://nodejs.org/),便可以看到首页的“INSTALL” ...
- PHP学习笔记:MySQL数据库的操纵
Update语句 Update 表名 set 字段1=值1, 字段2=值2 where 条件 练习: 把用户名带 ‘小’的人的密码设置为123456@ 语句:UPDATE crm_user SE ...
- 如何使用mybatis《二》
前边阐述了如何在java项目中使用mybatis,我们使用的是映射文件的方式,在获得具体的数据操作方法时需要传入映射文件中namespace+“.”方法名称,这种方式有时候会感觉很不爽,很麻烦.我们在 ...
- 字典集合Dictionary<K,V>和构造的应用==>>体检套餐项目
效果 首先,我们先来准备我们需要的类 1.检查项目类 using System; using System.Collections.Generic; using System.Linq; using ...
- 关于SQL Server的WITH(NOLOCK)和(NOLOCK)
The difference is that you should be using the syntax WITH (NOLOCK) (or WITH (<any table hint> ...
- 我所了解的WEB开发 (1)
开始接触网站开发的时候,概念里就对静态网站和动态网站有了简单的区分,静态网站仅仅是纯粹的HTML网页,动态网站是需要采用asp 连接数据库(比如access).那个时候听说高手都是使用 Notepad ...
- jDiameter介绍以及使用
jDiameter是Diameter协议的开源实现(比较不幸的是AGPL 3.0协议),项目地址https://github.com/RestComm/jdiameter. 项目框架 jDiamete ...
- HTML Jquery
在<网页制作Dreamweaver(悬浮动态分层导航)>中,运用到了jQuery的技术,轻松实现了菜单的下拉.显示.隐藏的效果,不必再用样式表一点点地修改,省去了很多麻烦,那么jQuery ...