Java中Logging的基本用法

合集下载

Java中的日志处理与调试技巧

Java中的日志处理与调试技巧

Java中的日志处理与调试技巧在Java开发中,日志处理和调试技巧是非常重要的。

良好的日志记录和调试技巧可以帮助开发人员追踪问题、定位错误,并且提高代码的可维护性。

本文将介绍一些Java中常用的日志处理和调试技巧。

一、日志处理技巧1. 使用日志框架Java中有许多优秀的日志框架可供选择,比如Log4j、Logback和java.util.logging等。

这些日志框架提供了丰富的功能和灵活的配置方式,可以满足不同场景的需求。

开发人员可以选择一个适合自己的日志框架,并根据需求配置日志输出的格式、级别和目标。

2. 使用适当的日志级别在编写日志时,应该根据重要性和详细程度选择适当的日志级别。

常见的日志级别有TRACE、DEBUG、INFO、WARN和ERROR等。

一般来说,TRACE和DEBUG用于调试和开发阶段,INFO用于输出程序运行的关键信息,WARN用于警告信息,ERROR用于输出错误信息。

通过选择适当的日志级别,可以提高日志的可读性和定位问题的效率。

3. 利用日志的上下文信息日志框架通常提供了上下文信息的功能,开发人员可以通过在日志中记录关键的上下文信息,来帮助追踪问题。

比如可以记录请求的URL、用户的身份信息等。

在进行线程池、并发处理等情况下,还可以记录线程的ID和名称等。

4. 异常处理与日志记录在捕获异常时,应该及时记录异常信息,并结合其他上下文信息进行日志记录。

通过记录异常信息,可以帮助开发人员追踪问题并及时修复错误。

二、调试技巧1. 使用断点调试在开发过程中,可以使用断点调试工具来定位问题。

通过设置断点,可以在程序执行到指定的位置时暂停程序的运行,并查看变量的值、程序的执行流程等。

断点调试是一种非常有用的调试技巧,可以帮助开发人员快速定位问题并修改代码。

2. 日志输出调试信息除了使用断点调试,还可以通过在关键位置输出调试信息的方式进行调试。

通过记录变量的值、方法的执行流程等信息,可以帮助开发人员理解程序的执行过程,并找出问题所在。

Logger用法

Logger用法

Logger⽤法1. logger的输出有两种⽅式:①log.log(,"message")②("mesage")其他级别的输出与此类似。

2. 获得com.sample.LoggerSample这个类的logger对象。

可设置其Level,这样在LoggerSample运⾏时会根据在LoggerSample中预先定义好的Level级别来输出log。

3. 设置logger输出级别各级别按降序排列如下:SEVERE(最⾼值)WARNINGINFOCONFIGFINEFINERFINEST(最低值)此外,还有⼀个级别 OFF,可⽤来关闭⽇志记录,使⽤级别 ALL 启⽤所有消息的⽇志记录。

如设置的Level级别⽐预定义的输出级别⾼,则Level较低处的log就不会输出。

4. 可以给logger添加Handler来进⾏不同形式的输出:①FileHandler:输出到⽂件②ConsoleHandler:输出到控制台③SocketHandler:输出到⽹络public class loggerTest {/** 存放的⽂件夹 **/private static String file_name = "反馈⽇志";/*** 得到要记录的⽇志的路径及⽂件名称* @return*/private static String getLogName() {StringBuffer logPath = new StringBuffer();logPath.append(System.getProperty("user.home")); //⽤户的主⽬录logPath.append("\\"+file_name);File file = new File(logPath.toString());if (!file.exists())file.mkdir();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");logPath.append("\\"+sdf.format(new Date())+".log");return logPath.toString();}/*** 配置Logger对象输出⽇志⽂件路径* @param logger* @param level 在⽇志⽂件中输出level级别以上的信息* @throws SecurityException* @throws IOException*/public static void setLogingProperties(Logger logger, Level level) {FileHandler fh;try {fh = new FileHandler(getLogName(), true);logger.addHandler(fh);// ⽇志输出⽂件// logger.setLevel(level);fh.setFormatter(new SimpleFormatter());// 输出格式// logger.addHandler(new ConsoleHandler());//输出到控制台(默认都会输出到控制台通过logger.setUseParentHandlers(false)关掉) } catch (SecurityException e) {logger.log(Level.SEVERE, "安全性错误", e);} catch (IOException e) {logger.log(Level.SEVERE, "读取⽂件⽇志错误", e);}}public static void setLogingProperties(Logger logger) throws SecurityException, IOException {setLogingProperties(logger,Level.ALL);}public static void main(String[] args) {Logger logger = Logger.getLogger("log.text");try {loggerTest.setLogingProperties(logger);// logger.setUseParentHandlers(false); //不输出到控制台(放在输出语句之前)logger.log(,"aaaaa");logger.setLevel(Level.WARNING); //设置⽇志级别设置级别以下的不显⽰( logger默认的级别是INFO) logger.log(Level.WARNING, "ccccc");("bbbbb");} catch (SecurityException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}输出结果:⼗⼀⽉14, 20174:36:32下午 test.loggerTest main信息: aaaaa⼗⼀⽉14, 20174:36:32下午 test.loggerTest main警告: ccccc相应⽂件夹也会有对应⽂件。

Java标准日志工具Log4j的使用1(入门)

Java标准日志工具Log4j的使用1(入门)

Java标准日志工具Log4j的使用1(入门)Log4j 是事实上的 Java 标准日志工具。

会不会用 Log4j 在一定程度上可以说是衡量一个开发人员是否是一位合格的 Java 程序员的标准。

如果你是一名 Java 程序员,如果你还不会用 Log4j,那你真的很有必要读一下这篇文章了。

很多朋友反映想写程序日志,但是却不知道怎么把日志写到日志文件里,而且 Java 这方面的资料似乎不多。

如《如何写log4j.xml日志配置文件》所述。

本文详细介绍了如何在项目中使用 Log4j 的步骤,并附加了一个例子性质的代码。

Why Log4j?有的朋友喜欢用System.out.println(String msg); 语句来调试代码。

这个确实是一个很好的调试工具。

但是随着项目的结束,或者问题的解决,这些语句需要我们一个个地揪出来手工删除?《如何一次性删除所有的system.out.println语句》,这个帖子里的这位网友就遇到了这样一个问题。

全部都删除干净,问题又来了:如果以后又出现问题了该怎么办呢?难道再次添加,问题解决后再次查找到删除?使用Log4j 就可以很好地解决上面的问题和矛盾。

Log4j 有一个日志级别,用来控制是否进行日志记录。

其由低到高的级别如下:ALL < DEBUG < INFO < WARN < ERROR < FATAL < OFF将日志进行分级的目的就是在于可以灵活配置。

比如说如果日志级别限定于DEBUG,那么包括DEBUG 在内的,INFO、WARN、ERROR、FATAL、OFF 都会进行日志记录;而如果级别定义为INFO,那么INFO 以下的级别,像DEBUG 的日志就不会记录。

比如如下代码:view plaincopy to clipboardprint?1.Logger log = LogManager.getLogger(HelloWorld.class);("info通过 class 对象来获取 logger 对象");3.log.debug("debug通过 class 对象来获取 logger 对象");4.log.warn("warn通过 class 对象来获取 logger 对象");如果你的 Log4j 定义为输出到控制台,日志级别定义为 INFO,那么执行到上面语句块,控制台会输出以下日志信息:18:07:37,237 INFOHelloWorld:32 - info通过 class 对象来获取logger 对象18:07:37,245 WARNHelloWorld:34 - warn通过 class 对象来获取 logger 对象具体范例作者已经上传至附件,有兴趣的朋友可以去下载下来看看。

Log4J教程:Java日志记录框架的基础功能介绍说明书

Log4J教程:Java日志记录框架的基础功能介绍说明书

About the T utorialLog4j is a popular logging package written in Java. Log4J is ported to the C, C++, C#, Perl, Python, Ruby, and Eiffel languages.AudienceThis tutorial is prepared for beginners to help them understand the basic functionality of Log4J logging framework.PrerequisitesAs you are going to use Log4J logging framework in various Java-based application development, it is imperative that you should have a good understanding of Java programming language.Copyright & DisclaimerCopyright 2015 by Tutorials Point (I) Pvt. Ltd.All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish any contents or a part of contents of this e-book in any manner without written consent of the publisher.We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our website or its contents including this tutorial. If you discover any errors on our website or in this tutorial, ******************************************iT able of ContentsAbout the Tutorial (i)Audience (i)Prerequisites (i)Copyright & Disclaimer (i)Table of Contents .......................................................................................................................................... i i 1.OVERVIEW .. (1)History of log4j (1)log4j Features (1)Pros and Cons of Logging (2)2.INSTALLATION (3)3.ARCHITECTURE (5)Core Objects (5)Support Objects (6)4.CONFIGURATION (8)log4j.properties Syntax (8)log4j.properties Example (8)Debug Level (9)Appenders (9)Layout (11)Layout Formatting (11)5.SAMPLE PROGRAM (12)Using log4j in Java Program (12)Compile and Execute (13)ii6.LOGGING METHODS (14)Logging Methods (14)7.LOGGING LEVELS (16)How do Levels Work? (16)Setting Levels using Configuration File (17)8.LOG FORMATTING (19)The Layout Types (19)HTMLLayout (19)PatternLayout (21)The Layout Methods (24)9.LOGGING IN FILES (26)FileAppender Configuration (26)Logging in Multiple Files (28)Daily Log File Generation (29)10.LOGGING IN DATABASE (32)JDBCAppender Configuration (32)Log Table Configuration (32)Sample Configuration File (33)Sample Program (34)Compile and Execute (35)iiiLog4J4Log4j is a reliable, fast, and flexible logging framework (APIs) written in Java, which is distributed under the Apache Software License.Log4j has been ported to the C, C++, C#, Perl, Python, Ruby, and Eiffel languages. Log4j is highly configurable through external configuration files at runtime. It views the logging process in terms of levels of priorities and offers mechanisms to direct logging information to a great variety of destinations, such as a database, file, console, UNIX Syslog, etc.Log4j has three main components:∙loggers: Responsible for capturing logging information. ∙ appenders: Responsible for publishing logging information to various preferred destinations.∙layouts: Responsible for formatting logging information in different styles. History of log4j∙ Started in early 1996 as tracing API for the E.U. SEMPER (Secure Electronic Marketplace for Europe) project.∙ After countless enhancements and several incarnations, the initial API has evolved to become log4j, a popular logging package for Java.∙ The package is distributed under the Apache Software License, a full-fledged open source license certified by the open source initiative.∙The latest log4j version, including its full-source code, class files, and documentation can be found at /log4j/. log4j Features∙It is thread-safe. ∙It is optimized for speed. ∙It is based on a named logger hierarchy. ∙It supports multiple output appenders per logger. 1.Log4J5∙It supports internationalization.∙It is not restricted to a predefined set of facilities.∙Logging behavior can be set at runtime using a configuration file.∙It is designed to handle Java Exceptions from the start.∙It uses multiple levels, namely ALL, TRACE, DEBUG, INFO, WARN, ERROR, and FATAL.∙The format of the log output can be easily changed by extending the Layout class.∙The target of the log output as well as the writing strategy can be altered by implementations of the Appender interface.∙It is fail-stop. However, although it certainly strives to ensure delivery, log4j does not guarantee that each log statement will be delivered to its destination.Pros and Cons of LoggingLogging is an important component of the software development. A well-written logging code offers quick debugging, easy maintenance, and structured storage of an application's runtime information.Logging does have its drawbacks also. It can slow down an application. If too verbose, it can cause scrolling blindness. To alleviate these concerns, log4j is designed to be reliable, fast, and extensible.Since logging is rarely the main focus of an application, the log4j API strives to be simple to understand and to use.Log4JLog4j API package is distributed under the Apache Software License, a full-fledged open source license certified by the open source initiative.The latest log4j version, including its full-source code, class files, and documentation can be found at /log4j/.To install log4j on your system, download apache-log4j-x.x.x.tar.gz from the specified URL and follow the steps given below.Step 1Unzip and untar the downloaded file in /usr/local/ directory as follows: While untarring, it would create a directory hierarchy with a name apache-log4j-x.x.x as follows:2.Log4J7Step 2This step is optional and depends on what features you are going to use from log4j framework. If you already have following packages installed on your machine then it is fine, otherwise you need to install them to make log4j work.∙JavaMail API:The e-mail based logging feature in log4j requires the Java Mail API (mail.jar) to be installed on your machine from https:///javaee5/mail/.∙JavaBeans Activation Framework:The Java Mail API will also require that the JavaBeans Activation Framework (activation.jar) be installed on your machine from /products/javabeans/jaf/index.jsp.∙Java Message Service:The JMS-compatible features of log4j will require that both JMS and Java Naming and Directory Interface (JNDI) be installed on your machine from /products/jms.∙XML Parser:You need a JAXP-compatible XML parser to use log4j. Make sure you have Xerces.jar installed on your machine from /xerces-j/install.html.Step 3Now you need to set up the CLASSPATH and PATH variables appropriately. Here we are going to set it just for the log4j.x.x.x.jar file.Log4J 8Log4j API follows a layered architecture where each layer provides different objects to perform different tasks. This layered architecture makes the design flexible and easy to extend in future.There are two types of objects available with Log4j framework:∙ Core Objects: These are mandatory objects of the framework. They are required to use the framework.∙Support Objects: These are optional objects of the framework. They support core objects to perform additional but important tasks. Core ObjectsCore objects include the following types of objects:Logger ObjectThe top-level layer is the Logger which provides the Logger object. The Logger object is responsible for capturing logging information and they are stored in a namespace hierarchy. Layout ObjectThe Layout layer provides objects which are used to format logging information in different styles. It provides support to appender objects before publishing logging information. Layout objects play an important role in publishing logging information in a way that is human-readable and reusable.Appender ObjectThis is a lower-level layer which provides Appender objects. The Appender object is responsible for publishing logging information to various preferred destinations such as a database, file, console, UNIX Syslog, etc.The following virtual diagram shows the components of a log4j framework:3.Log4J9Support ObjectsThere are other important objects in the log4j framework that play a vital role in the logging framework:Level ObjectThe Level object defines the granularity and priority of any logging information. There are seven levels of logging defined within the API: OFF, DEBUG, INFO, ERROR, WARN, FATAL, and ALL.Filter ObjectThe Filter object is used to analyze logging information and make further decisions on whether that information should be logged or not.An Appender objects can have several Filter objects associated with them. If logging information is passed to a particular Appender object, all the Filter objects associated with that Appender need to approve the logging information before it can be published to theattached destination.Log4J10ObjectRendererThe ObjectRenderer object is specialized in providing a String representation of different objects passed to the logging framework. This object is used by Layout objects to prepare the final logging information.LogManagerThe LogManager object manages the logging framework. It is responsible for reading the initial configuration parameters from a system-wide configuration file or a configuration class.Log4J11 The previous chapter explained the core components of log4j. This chapter explains how you can configure the core components using a configuration file. Configuring log4j involves assigning the Level, defining Appender, and specifying Layout objects in a configuration file. The log4j.properties file is a log4j configuration file which keeps properties in key-value pairs. By default, the LogManager looks for a file named log4j.properties in the CLASSPATH. ∙The level of the root logger is defined as DEBUG. The DEBUG attaches the appender named X to it.∙Set the appender named X to be a valid appender. ∙ Set the layout for the appender X.log4j.properties SyntaxFollowing is the syntax of log4j.properties file for an appender X:log4j.properties ExampleUsing the above syntax, we define the following in log4j.properties file:∙ The level of the root logger is defined as DEBUG. The DEBUG the appender named FILE to it.∙ The appender FILE is defined as org.apache.log4j.FileAppender . It writes to a file named "log.out" located in the log directory.4.12∙The layout pattern defined is %m%n, which means the printed logging message will be followed by a newline character.It is important to note that log4j supports UNIX-style variable substitution suchas${variableName}.Debug LevelWe have used DEBUG with both the appenders. All the possible options are: ∙TRACE∙DEBUG∙INFO∙WARN∙ERROR∙FATAL∙ALLThese levels would be explained inAppendersApache log4j provides Appender objects which are primarily responsible for printing logging messages to different destinations such as consoles, files, sockets, NT event logs, etc.Each Appender object has different properties associated with it, and these properties indicate the behavior of that object.13We can add an Appender object to a Logger by including the following setting in the configuration file with the following method:You can write same configuration in XML format as follows:If you are willing to add Appender object inside your program then you can use following method:The addAppender() method adds an Appender to the Logger object. As the example configuration demonstrates, it is possible to add many Appender objects to a logger in a comma-separated list, each printing logging information to separate destinations.14We have used only one appender FileAppender in our example above. All the possible appender options are:∙AppenderSkeleton∙AsyncAppender∙ConsoleAppender∙DailyRollingFileAppender∙ExternallyRolledFileAppender∙FileAppender∙JDBCAppender∙JMSAppender∙LF5Appender∙NTEventLogAppender∙NullAppender∙RollingFileAppender∙SMTPAppender∙SocketAppender∙SocketHubAppender∙SyslogAppender∙TelnetAppender∙WriterAppenderLayoutWe have used PatternLayout with our appender. All the possible options are: ∙DateLayout∙HTMLLayout∙PatternLayout∙SimpleLayout∙XMLLayoutUsing HTMLLayout and XMLLayout, you can generate log in HTML and in XML format as well.Log4J15Layout FormattingLog4J We have seen how to create a configuration file. This chapter describes how to generate debug messages and log them in a simple text file.Following is a simple configuration file created for our example. Let us revise it once again: ∙ The level of the root logger is defined as DEBUG and attaches appender named FILE to it.∙ The appender FILE is defined as org.apache.log4j.FileAppender and writes to a file named "log.out" located in the log directory.∙The layout pattern defined is %m%n, which means the printed logging message will be followed by a newline character. The contents of log4j.properties file are as follows:Using log4j in Java ProgramThe following Java class is a very simple example that initializes and then uses the Log4J logging library for Java applications.5.Log4J17Compile and ExecuteHere are the steps to compile and run the above-mentioned program. Make sure you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution. All the libraries should be available in CLASSPATH and your log4j.properties file should be available in PATH. Follow the steps given below:∙Create log4j.properties as shown above. ∙Create log4jExample.java as shown above and compile it. ∙ Execute log4jExample binary to run the program.You would get the following result inside /usr/home/log4j/log.out file:Log4J 18Logger class provides a variety of methods to handle logging activities. The Logger class does not allow us to instantiate a new Logger instance but it provides two static methods for obtaining a Logger object:∙public static Logger getRootLogger(); ∙ public static Logger getLogger(String name);The first of the two methods returns the application instance's root logger and it does not have a name.Any other named Logger object instance is obtained through the second method by passing the name of the logger. The name of the logger can be any string you can pass, usually a class or a package name as we have used in the last chapter and it is mentioned below: Logging MethodsOnce we obtain an instance of a named logger, we can use several methods of the logger to log messages. The Logger class has the following methods for printing the logging information.6.Log4J19All the levels are defined in the org.apache.log4j.Level class and any of the above-mentioned methods can be called as follows:When you compile and run LogClass program, it would generate the following result:20All the debug messages make more sense when they are used in combination with levels. We will cover levels in the next chapter and then, you would have a good understanding of how to use these methods in combination with different levels of debugging.21End of ebook previewIf you liked what you saw…Buy it from our store @ https://。

java 日志打印中 {}用法

java 日志打印中 {}用法

一、概述在Java开发中,日志打印起着至关重要的作用,它能够方便开发人员在调试和排查问题时快速定位到特定的代码段,从而加快开发和维护的效率。

在日志打印中,{}用法是一个非常常见的技巧,它能够方便地将变量的值嵌入到日志信息中,使得日志更加丰富和具有可读性。

本文将围绕Java日志打印中{}用法展开详细的讨论并举例说明。

二、{}用法的基本语法在Java的日志打印中,通常使用的是slf4j作为日志门面,具体的日志实现可以是logback、log4j等。

在使用这些日志框架的过程中,{}用法通常是这样的:在打印日志的字符串中使用{}作为占位符,并在后面的参数中依次传入{}中应该代替的值。

例如:```java("User {} login success.", userName);```在这个例子中,{}被用作占位符,而userName则是需要在日志中打印的实际值。

三、{}用法的优点1. 代码可读性强:使用{}占位符能够更加清晰地表达日志打印的格式,使得代码的可读性大大提高。

2. 降低字符串连接的复杂度:如果不使用{}占位符,很可能会出现大量的字符串连接操作,而使用{}则能够避免这种情况,提高代码的执行效率。

3. 方便日志级别控制:使用{}占位符能够方便地控制日志的输出级别,如果日志级别过低,只需要简单的更改日志级别,而无需修改日志打印的具体内容。

四、{}用法的实际应用在实际的开发中,{}占位符的应用非常广泛,下面举几个常见的例子来说明它的实际应用场景。

1. 打印错误信息```javalogger.error("An error occurred while processing the request, error code: {}", errorCode);```在这个例子中,使用{}占位符来打印错误码,使得日志信息更加详细,方便开发人员定位问题。

2. 打印方法参数```javalogger.debug("Method getUserInfo called with parameters: username={}, age={}", username, age);```在这个例子中,使用{}占位符来打印方法的参数,使得在调试的时候能够清晰地看到方法被调用时的具体参数值。

Log4j日志在java项目中的使用(附工程源码)

Log4j日志在java项目中的使用(附工程源码)

Log4j⽇志在java项⽬中的使⽤(附⼯程源码)⼀、关于Log4j⽇志Log4j是Apache的⼀个开源项⽬,通过使⽤Log4j,我们可以控制⽇志信息输送的⽬的地是控制台、⽂件、GUI组件,甚⾄是套接⼝服务器、NT的事件记录器、UNIX Syslog守护进程等;我们也可以控制每⼀条⽇志的输出格式;通过定义每⼀条⽇志信息的级别,我们能够更加细致地控制⽇志的⽣成过程。最令⼈感兴趣的就是,这些可以通过⼀个配置⽂件来灵活地进⾏配置,⽽不需要修改应⽤的代码。

在强调可重⽤组件开发的今天,除了⾃⼰从头到尾开发⼀个可重⽤的⽇志操作类外,Apache为我们提供了⼀个强有⼒的⽇志操作包-Log4j。此外,通过Log4j其他语⾔接⼝,您可以在C、C++、.Net、PL/SQL程序中使⽤Log4j,其语法和⽤法与在Java程序中⼀样,使得多语⾔分布式系统得到⼀个统⼀⼀致的⽇志组件模块。⽽且,通过使⽤各种第三⽅扩展,您可以很⽅便地将Log4j集成到J2EE、JINI甚⾄是SNMP应⽤中。

⼆、Log4j使⽤前必须要了解的⼀些概念2.1、⽇志信息的优先级⽇志记录的优先级,分为OFF、FATAL、ERROR、WARN、INFO、DEBUG、ALL或者您定义的级别。Log4j建议只使⽤四个级别,优 先级从⾼到低分别是ERROR、WARN、INFO、DEBUG。⽽且在企业中⼀般也只使⽤着四种。下⾯是各个级别的极介绍:

OFF 最⾼等级,⽤于关闭所有⽇志记录。 FATAL 指出每个严重的错误事件将会导致应⽤程序的退出。 ERROR 指出虽然发⽣错误事件,但仍然不影响系统的继续运⾏。 WARN 表明会出现潜在的错误情形。 INFO ⼀般和在粗粒度级别上,强调应⽤程序的运⾏全程。 DEBUG ⼀般⽤于细粒度级别上,对调试应⽤程序⾮常有帮助。 ALL 最低等级,⽤于打开所有⽇志记录。

2.2、⽇志信息的输出⽬的地⽇志信息的输出⽬的地指定了⽇志将打印到控制台还是⽂件中。参考如下配置⽂件log4j.properties,其既配置了输出到控制台,也配置了输出到⽇志⽂件中:### 设置###log4j.rootLogger = debug,stdout,D,E

log4j基本使用方法

log4j是一个非常强大的log记录软件,下面我们就来看看在项目中如何使log4j。

首先当然是得到log4j的jar档,推荐使用1.2.X版,下载地址:/log4j/1.2/download.html我们先看一个最简单的示例:【示例1】项目结构:【注:由于这里的多个项目公用一个jar档,我们可以创建一个专门放置jar档的Java工程,然后将jar档放到lib目录下。

在要使用的工程中按图所示进行引用】Java代码:Java代码1package com.coderdream.log4j;23import org.apache.log4j.Logger;45public class HelloLog4j {67private static Logger logger = Logger.getLogger(HelloLog4j.class);89/**10* @param args11*/12public static void main(String[] args) {13// System.out.println("This is println message.");1415// 记录debug级别的信息16logger.debug("This is debug message.");17// 记录info级别的信息("This is info message.");19// 记录error级别的信息20logger.error("This is error message.");21}22}配置文件log4j.properties:Properties代码23#可以设置级别:debug>info>error24#debug:显示debug、info、error25#info:显示info、error26#error:只error27log4j.rootLogger=debug,appender128#log4j.rootLogger=info,appender129#log4j.rootLogger=error,appender13031#输出到控制台32log4j.appender.appender1=org.apache.log4j.ConsoleAppender33#样式为TTCCLayoutyout=org.apache.log4j.TTCCLayout输出结果:Console代码35[main] DEBUG com.coderdream.log4j.HelloLog4j - This is debug message.36[main] INFO com.coderdream.log4j.HelloLog4j - This is info message.37[main] ERROR com.coderdream.log4j.HelloLog4j - This is error message. 通过配置文件可知,我们需要配置3个方面的内容:1、根目录(级别和目的地);2、目的地(控制台、文件等等);3、输出样式。

JAVA中使用log4j及slf4j进行日志输出的方法详解

JAVA中使⽤log4j及slf4j进⾏⽇志输出的⽅法详解 JAVA中输出⽇志⽐较常⽤的是log4j,这⾥讲下log4j的配置和使⽤⽅法,以及slf4j的使⽤⽅法。

⼀、下载log4j的架包,并导⼊项⽬中,如下:⼆、创建log4j.properties配置⽂件1、log4j配置⽂件的位置:(1)如果是java project项⽬,则在项⽬的根⽬录下创建log4j.properties⽽不是在src⽬录下。

(2)如果是java web项⽬,则在src⽬录下创建log4j.properties配置⽂件,因为这个时候tomcat会去默认的加载这个配置⽂件,⽽不需要我们⼿动的加载log4j的配置⽂件。

log4j.properties配置内容如下:1 log4j.rootLogger=info,logTest2 log4j.appender.logTest=org.apache.log4j.DailyRollingFileAppender3 log4j.appender.logTest.File=/logs/LogTest/logTest.log4 log4j.appender.logTest.DatePattern='.'yyyy-MM-dd'.log'5 yout=org.apache.log4j.PatternLayout6 yout.ConversionPattern=[LogTestInfo] [%d][%c][%-5p]%m%n2、log4j配置项的说明:(1)第⼀⾏中rootLogger配置的是整个项⽬的⽇志输出,也可以只针对某⼀个模块进⾏⽇志输出,⽐如第⼀⾏配置成.logTest.project=info,logTest,则⽇志只输出项⽬路径com/logTest/project下的。

info为⽇志级别,可分为OFF、FATAL、ERROR、WARN、INFO、DEBUG、ALL。

logger用法

logger用法logger用法:Logger是一种用于记录日志信息的工具,可以帮助开发人员调试应用程序,增强系统安全性。

使用logger可以有效地将系统中发生的重要事件、警告和错误信息记录到日志文件中,并方便查看和分析日志文件。

logger的使用步骤:1、首先,需要将logger日志模块导入程序中,一般会使用Python标准库中的logging模块。

2、然后,需要在程序中创建一个logger对象,可以使用logging模块中的getLogger()函数来创建logger对象。

3、之后,需要为logger对象设置相应的日志级别,常用的日志级别有debug、info、warning、error和critical五种。

4、接着,需要指定将日志写入到哪种日志文件中,一般情况下,会选择将日志信息写入到文本文件中,可以使用StreamHandler、FileHandler或TimedRotatingFileHandler等处理器来实现这一功能。

5、最后,需要在程序中调用logger对象的各种方法,如debug()、info()、warning()、error()和critical()等,来记录日志信息。

logger的优点:1、logger支持多种不同的日志记录方式,如日志输出到文本文件、控制台等,可以根据需要自由组合,满足不同的日志记录需求。

2、logger可以根据日志级别,仅记录重要的日志信息,从而极大地减少日志文件的大小,增强程序的运行性能。

3、logger可以记录日志文件的位置,方便查看和分析日志文件,从而更好地调试程序,增强系统的安全性。

logger的缺点:1、logger会占用比较多的磁盘空间,如果日志文件过大,可能会对系统性能造成不利影响。

2、logger一般只能记录系统事件,不能直接检测到系统中发生的故障。

因此,使用logger时,需要根据日志信息来分析系统故障,这往往需要开发人员的专业能力。

tomcat logging 级别

tomcat logging 级别
Tomcat 是一个开源的 Java Web 服务器和 servlet 容器,它提供了几种不同的日志记录级别,用于控制日志消息的详细程度。

这些日志级别包括:
- FATAL:表示严重的错误,导致应用程序无法继续运行。

- ERROR:表示错误情况,但应用程序可以继续运行。

- WARN:表示可能会出现问题,但不一定是错误。

- INFO:表示一般信息,用于监控应用程序的运行状态。

- DEBUG:表示详细的调试信息,通常用于开发和调试阶段。

通过设置不同的日志级别,可以控制 Tomcat 记录的日志消息的详细程度。

例如,可以将日志级别设置为 WARN,只记录警告和错误消息,而不会记录 INFO 和 DEBUG 消息,以减少日志量和提高性能。

要设置 Tomcat 的日志级别,可以通过修改 Tomcat 的配置文件来完成。

具体的配置文件位置和名称可能因操作系统和 Tomcat 版本而有所不同,但通常可以在 Tomcat 的安装目录下找到名为 catalina.properties 的文件。

在 catalina.properties 文件中,可以找到以下行:
```properties
logging.level.=INFO
```
将其修改为所需的日志级别,例如:
```properties
logging.level.=WARN
```
保存并重新启动 Tomcat,新的日志级别将生效。

需要注意的是,设置较高的日志级别可能会导致日志量增加,因此在生产环境中应根据实际需要选择适当的日志级别。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

有关logging这个Jar包的使用,最近由于接触一个新的项目,是有关Java和数据库的,涉及到logging的使
用,在这里简单记载,以供大家学习和自己整理而用。

在这里用一个例子讲述,会在制定的路径下面生成一个test.log文件,并将程序中需要打印的语句输出到log
文件中。PS:这个例子是基于Oracle JDeveloper进行编写的。

首先在工程中引入相关的Jar包,这里主要指:commons-logging.jar 。 导入结果如下图所示:

然后在程序的开头引入:
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

class Logging{
Logger oLogger = Logger.getLogger(Logging.class.getName());
FileHandler oLogFileHandler = null;
//这个函数是将传进来的String输出到log文件里面。
public void LogExecution(String mstrTemp){
try{
if(oLogFileHandler == null){
String strLogPath = "D:¥¥test.log";//此处为log文件路径
oLogFileHandler = new FileHandler(strLogPath,true);
oLogger.addHandler(oLogFileHandler);
oLogger.setLevel(Level.ALL);
}
oLogger.info("ATTENTION:"+mstrTemp);
// return true;
} catch (IOException e) {
oLogger.info("In catch : Error!!!");
// return false;
}/* finally{
strResult = "Finallly Block";
oLogger.info("In finally" + strResult);
}*/
}
}

Logging这个类写好以后,你就可以在其他地方对其进行调用:
public static void main(String[] args)
{
Logging oLogging = new Logging();
oLogging.LogExecution("程序开始。");
oLogging.LogExecution("连接Postgres数据库成功。");
oLogging.LogExecution("关闭Postgres数据库连接。");
oLogging.LogExecution("程序结束。");
}
在控制台上显示为:

在生成的test.log文件中显示为:

相关文档
最新文档