`
transray
  • 浏览: 39274 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

How to use Log4j

阅读更多
1、 Log4j是什么?
  Log4j可以帮助调试(有时候debug是发挥不了作 用的)和分析,要下载和了解更详细的内容,还是访问其官方网站吧: http://jakarta.apache.org/log4j 。

2、Log4j的概念
   Log4j中有三个主要的组件,它们分别是 Logger、Appender和Layout,Log4j 允许开发人员定义多个Logger,每个Logger拥有自己的名字,Logger之间通过名字来表明隶属关系。有一个Logger称为Root,它永远存在,且不能通过名字检索或引用,可以通过Logger.getRootLogger()方法获得,其它Logger通过 Logger.getLogger(String name)方法。
   Appender则是用来指明将所有的log信息存放到什么地方,Log4j中支持多种appender,如 console、files、GUI components、NT Event Loggers等,一个Logger可以拥有多个Appender,也就是你既可以将Log信息输出到屏幕,同时存储到一个文件中。
   Layout的作用是控制Log信息的输出方式,也就是格式化输出的信息。
   Log4j中将要输出的Log信息定义了5种级别,依次为DEBUG、INFO、WARN、ERROR和FATAL,当输出时,只有级别高过配置中规定的级别的信息才能真正的输出,这样就很方便的来配置不同情况下要输出的内容,而不需要更改代码,这点实在是方便啊。

3、Log4j的配置文件
  虽然可以不用配置文件,而在程序中实现配置,但这种方法在如今的系统开发中显然是不可取的,能采用配置文件的地方一定一定要用配置文件。Log4j支持两种格式的配置文件:XML格式和Java的property格式,本人更喜欢后者,首先看一个简单的例子吧,如下:

  log4j.rootLogger=debug, stdout, R
  log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

  # Pattern to output the caller's file name and line number.
  log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

  log4j.appender.R=org.apache.log4j.RollingFileAppender
  log4j.appender.R.File=example.log
  log4j.appender.R.MaxFileSize= 100KB

  # Keep one backup file
  log4j.appender.R.MaxBackupIndex=1

  log4j.appender.R.layout=org.apache.log4j.PatternLayout
  log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n        

  首先,是设置root,格式为 log4j.rootLogger=[level],appenderName, ...,其中level就是设置需要输出信息的级别,后面是appender的输出的目的地,appenderName就是指定日志信息输出到哪个地方。您可以同时指定多个输出目的地。 配置日志信息输出目的地Appender,其语法为
  log4j.appender.appenderName = fully.qualified.name.of.appender.class
  log4j.appender.appenderName.option1 = value1
  ...
  log4j.appender.appenderName.option = valueN
Log4j提供的appender有以下几种:
  org.apache.log4j.ConsoleAppender(控制台)
  org.apache.log4j.FileAppender(文件)
  org.apache.log4j.DailyRollingFileAppender(每天产生一个日志文件)
  org.apache.log4j.RollingFileAppender(文件大小到达指定尺寸的时候产生新文件)
  org.apache.log4j.WriterAppender(将日志信息以流格式发送到任意指定的地方)
配置日志信息的格式(布局),其语法为:
  log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class
  log4j.appender.appenderName.layout.option1 = value1
  ....
  log4j.appender.appenderName.layout.option = valueN
Log4j提供的layout有以下几种:
  org.apache.log4j.HTMLLayout(以HTML表格形式布局),
  org.apache.log4j.PatternLayout(可以灵活地指定布局模式),
  org.apache.log4j.SimpleLayout(包含日志信息的级别和信息字符串),
  org.apache.log4j.TTCCLayout(包含日志产生的时间、线程、类别等等信息)

Log4J采用类似C语言中的printf函数的打印格式格式化日志信息,打印参数如下: %m 输出代码中指定的消息
   %p 输出优先级,即DEBUG,INFO,WARN,ERROR,FATAL
  %r 输出自应用启动到输出该log信息耗费的毫秒数
  %c 输出所属的类目,通常就是所在类的全名
  %t 输出产生该日志事件的线程名
  %n 输出一个回车换行符,Windows平台为“\r\n”,Unix平台为“\n”
  %d 输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式,比如:%d{yyy MMM dd HH:mm:ss,SSS},输出类似: 2002年10月18日 22:10:28,921
  %l 输出日志事件的发生位置,包括类目名、发生的线程,以及在代码中的行数。举例:Testlog4.main(TestLog4.java:10)



4、Log4j在程序中的使用
  要在自己的程序中使用Log4j,首先需要将commons-logging.jar和logging-log4j-1.2.9.jar导入到构建路径中。然后再将log4j.properties放到src根目录下。这样就可以在程序中使用log4j了。在类中使用log4j, 首先声明一个静态变量 Logger logger=Logger.getLog("classname");现在就可以使用了,用法如下:logger.debug("debug message")或者logger.info("info message"),看下面一个小例子:

  import com.foo.Bar;
  import org.apache.log4j.Logger;
  import org.apache.log4j.PropertyConfigurator;
  public class MyApp {
    static Logger logger = Logger.getLogger(MyApp.class.getName());
    public static void main(String[] args) {
      // BasicConfigurator replaced with PropertyConfigurator.
      PropertyConfigurator.configure(args[0]);
      logger.info("Entering application.");
      Bar bar = new Bar();
      bar.doIt();
      logger.info("Exiting application.");
    }
  }

分享到:
评论

相关推荐

    erlang日志应用log4erl(非sasl)

    - Support for a log formatter (similar to Layouts in Log4J) - Support for console log - Support for smtp formatter - Support for XML logs - Support for syslog - Support for changing format and level ...

    Java 9 Revealed: For Early Adoption and Migration

    Walking APIUse the jlink tool to create a custom runtime imageWork ...log messages from platform classes and how to use JVM logsLearn about new methods in the Optional class and how to use themLearn how...

    SharePoint 2010 How-To

    SharePoint® 2010 How-To Ishai Sagi Real Solutions for SharePoint 2010 Users Need fast, reliable, easy-to-implement solutions for SharePoint 2010? This book delivers exactly what you’re looking ...

    Beginning.Elastic.Stack

    This book teaches you how to install, configure and implement the Elastic Stack (Elasticsearch, Logstash and Kibana) – the invaluable tool for anyone deploying a centralized log management solution ...

    spring.microservices.in.action

    Chapter 9 shows how to implement common logging patterns such as log corre- lation, log aggregation, and tracing using Spring Cloud Sleuth and Open Zipkin. Chapter 10 is the cornerstone project for ...

    DevOps Automation Cookbook(PACKT,2015)

    This book takes a ... You will also discover how to filter data with Grafana and use InfluxDB along with unconventional log management. Finally, you will employ the Heroku and Amazon AWS platforms.

    C#学习的101个经典例子

    NET Framework - How-To Use the EventLog NET Framework - How-To Working with GDI+ Pens NET Framework - Read and Write Performance Counters NET Framework - Reading and Writing with a Text File ...

    Apache Flume Distributed Log Collection For Hadoop

    It will give you a heads-up on how to use channels and channel selectors. For each architectural component (Sources, Channels, Sinks, Channel Processors, Sink Groups, and so on) the various ...

    Apache Flume- Distributed Log Collection for Hadoop(PACKT,2013)

    It will give you a heads-up on how to use channels and channel selectors. For each architectural component (Sources, Channels, Sinks, Channel Processors, Sink Groups, and so on) the various ...

    mastering-spring-cloud2018

    learn how to use OAuth2 and JWT token to authorize requests coming to your API. Chapter 13, Testing Java Microservices, will describe different strategies of microservices testing. It will focus on ...

    go系统编程(英文版)

    how to perform various types of DNS lookups, and how to use Wireshark to inspect network traffic. Additionally, it talks about developing RPC clients and servers in Go as well as developing a Unix ...

    Learning.PowerCLI.2nd.Edition.epub

    Towards the end, you'll see how to use the REST APIs from PowerShell to manage NSX and vRealize Automation and create patch baselines, scan hosts against the baselines for missing patches, and re-...

    TestComplete Cookbook(PACKT,2013)

    TestComplete is an automated testing tool, designed for ...Understand how to use log formatting and log generation in a proper format Get to grips with how to work with non-standard controls elements

    NIST SP800-70r4.pdf

    This document describes the use, benefits, and management of checklists, and explains how to use the NIST National Checklist Program (NCP) to find and retrieve checklists. The document also describes ...

    UE(官方下载)

    How to use TaskMatch Environments in UltraEdit and UEStudio Configure FTP backup Save a local copy of your files when you transfer them to FTP directories Encrypt and Decrypt Text Files Use UltraEdit ...

    CakePHP 1.3 Application Development Cookbook.pdf

    recipe shows how to use the MagicDb class to detect the type of a file, and the last recipe shows how to create application exceptions, and properly handle them when they are thrown. What you need ...

    NIST SP800-70-rev2.pdf

    This document describes the use, benefits, and management of checklists, and explains how to use the NIST National Checklist Program (NCP) to find and retrieve checklists. The document also describes ...

    Foundations for Analytics with Python O-Reilly-2016-Clinton W. Brownley

    the main data containers (i.e., lists, tuples, and dictionaries) and how you use them to store and manipulate your data, as well as how to deal with dates, as dates often appear in business analysis....

    Apache Flume Distributed Log Collection for Hadoop(PACKT,2ed,2015)

    Apache Flume is a distributed, reliable, and available service used to efficiently collect, aggregate, and move large amounts of log data. It is used to stream logs from application servers to HDFS ...

    Embarcadero.Delphi.XE7 Update 1破解

    How to Use: 1 Install RAD Studio XE7UP1 RTM with generated Serial Number This is very important step Do not use any other serial numbers from internet 2 Click "Patch" 3 Enter your ...

Global site tag (gtag.js) - Google Analytics