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获取浏览器当前窗口的高度长度
js获取浏览器可见区域(不包括标题栏.地址栏.收藏夹栏状态栏等额外区域,仅为页面呈现区域)的高度和宽度宽度:document.documentElement.clientWidth高度:documen ...
- 正则表达式相关:C# 抓取网页类(获取网页中所有信息)
类的代码: using System; using System.Data; using System.Configuration; using System.Net; using System.IO ...
- 详细讲解PHP中缓存技术的应用
PHP,一门最近几年兴起的web设计脚本语言,由于它的强大和可伸缩性,近几年来得到长足的发展,php相比传统的asp网站,在速度上有绝对的优势,想mssql转6万条数据php如需要40秒,asp不下2 ...
- 译 PrestaShop开发者指南 第四篇 深入PrestaShop核心开发
## 访问数据库 ### 数据库结构 PrestaShop的数据库表默认带有ps_的前缀,前缀在安装时可以自定义. 所有表名都是小写,以下划线分割.当一个表表示要在两个实体间建立连接时,表名中两个实体 ...
- Python学习之Python简介
Python简介 Python的由来 Python(英国发音:/ˈpaɪθən/ 美国发音:/ˈpaɪθɑːn/), 是一种面向对象.解释型计算机程序设计语言,它是吉多·范罗苏姆(Guide van ...
- ahjesus 捕获entity framework生成的sql语句
网上这方面的资料很少,找到一个可以用的 http://code.msdn.microsoft.com/EFProviderWrappers 里面有dll可以下载,有教程,不过是E文的. 在Entity ...
- IOS网络编程之请求内容
资料均来自互联网,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任. 人魔七七:http://www.cnblogs.com/qiqibo/ 一个http请求只要由三 ...
- Javascript中的Label语句
在javascript中,我们可能很少会去用到 Label 语句,但是熟练的应用 Label 语句,尤其是在嵌套循环中熟练应用 break, continue 与 Label 可以精确的返回到你想要的 ...
- Creating a SharePoint BCS .NET Connectivity Assembly to Crawl RSS Data in Visual Studio 2010
from:http://blog.tallan.com/2012/07/18/creating-a-sharepoint-bcs-net-assembly-connector-to-crawl-rss ...
- Android DiskLruCache 硬盘缓存
概述 记得在很早之前,我有写过一篇文章Android高效加载大图.多图解决方案,有效避免程序OOM,这篇文章是翻译自Android Doc的,其中防止多图OOM的核心解决思路就是使用LruCache技 ...