TinyLog –轻量级Java日志记录框架教程

TinyLog是适用于Java、Kotlin、Scala和Android的简单轻量级日志库,提供了静态Logger类,避免了初始化的样板代码,并支持Kotlin和Scala等JVM语言。该框架体积小巧,输出可定向到控制台、文件、数据库,配置简单,且支持创建标签以过滤日志。TinyLog比Log4J更快,不依赖其他API,支持懒惰日志和滚动文件编写器配置。

TinyLog is a simple and lightweight logging framework for Java. We can use tinylog with Java, Kotlin, Scala, and Android applications.

TinyLog是Java的简单轻量级日志记录框架。 我们可以将tinylog与Java,Kotlin,Scala和Android应用程序一起使用。

TinyLog日志记录框架的好处 (Benefits of TinyLog Logging Framework)

  1. Avoids boiler-plate code of Logger initialization. The Logger class in tinylog is static and used directly to log messages.

    避免Logger初始化的样板代码。 tinylog中的Logger类是静态的,可直接用于记录消息。
  2. Support for other popular JVM languages such as Kotlin and Scala.

    支持其他流行的JVM语言,例如Kotlin和Scala。
  3. Support for android applications too using logcat.

    也支持使用logcat的android应用程序。
  4. The tinylog jars are lightweight and small in size. The tinylog 2.x version API jar is 48 kb and implementation jar is 72 kb only.

    tinylog罐子重量轻且尺寸小。 tinylog 2.x版本的API jar为48 kb,实现jar为72 kb。
  5. The output can be sent to Console, File, database using JDBC and DataSource.

    可以使用JDBC和DataSource将输出发送到控制台,文件,数据库。
  6. The configuration file is very simple. For simple console based logging, we don’t need any configuration file.

    配置文件非常简单。 对于基于控制台的简单日志记录,我们不需要任何配置文件。
  7. It’s free and open source. The complete project code is hosted on GitHub.

    它是免费和开源的。 完整的项目代码托管在GitHub上
  8. According to their own benchmarking, they are much faster than Log4J logging framework.

    根据他们自己的基准测试 ,它们比Log4J日志记录框架快得多。
  9. There is no dependency on any other API and framework.

    不依赖于任何其他API和框架。
  10. Support for creating tags to categorize the log messages. It’s very useful in filtering log messages from a huge log file.

    支持创建标签以对日志消息进行分类。 这对于从巨大的日志文件中过滤日志消息非常有用。
  11. Lazy Logging support to defer expensive computation only if the logging is required.

    懒惰日志支持仅在需要日志时才推迟昂贵的计算。

TinyLog日志入门 (Getting Started with the TinyLog Logging)

We have to include following jars into our project classpath. These are the latest versions of the tinylog framework as of writing this tutorial.

我们必须在项目类路径中包含以下jar。 这些是撰写本教程时tinylog框架的最新版本。

  • tinylog-api-2.0.0-RC1.jar

    tinylog-api-2.0.0-RC1.jar
  • tinylog-impl-2.0.0-RC1.jar

    tinylog-impl-2.0.0-RC1.jar

Most of the time, we use Maven or Gradle for our project build and dependencies management.

大多数时候,我们使用Maven或Gradle进行项目构建和依赖管理。

Minelog的Maven依赖关系 (Maven Dependencies for tinylog)

<dependency>
	<groupId>org.tinylog</groupId>
	<artifactId>tinylog-api</artifactId>
	<version>2.0.0-RC1</version>
</dependency>
<dependency>
	<groupId>org.tinylog</groupId>
	<artifactId>tinylog-impl</artifactId>
	<version>2.0.0-RC1</version>
</dependency>

tinylog的Gradle依赖关系 (Gradle Dependencies for tinylog)

implementation 'org.tinylog:tinylog-api:2.0.0-RC1'
implementation 'org.tinylog:tinylog-impl:2.0.0-RC1'
The above implementation jar is for JVM based applications. There are separate implementation jars for Kotlin, Scala, Android, SLF4J, and JCL. You have to include the implementation JAR based on the type of your project.
上面的实现jar适用于基于JVM的应用程序。 对于Kotlin,Scala,Android,SLF4J和JCL,有单独的实现jar。 您必须根据您的项目类型包括实施JAR。

使用tinylog记录器 (Using tinylog Logger)

Once the required jars are added to the project classpath, we can use its Logger class to write logging messages.

将所需的jar添加到项目类路径后,我们可以使用其Logger类编写日志消息。

Below image shows my Eclipse project structure.

下图显示了我的Eclipse项目结构。

Tinylog Example Project

TinyLog Example Project

TinyLog示例项目

Here are the classes where I am using tinylog Logger for logging.

这是我使用tinylog Logger进行记录的类。

Employee.java: A simple model class with some properties and their getter-setter methods.

Employee.java :一个简单的模型类,具有一些属性及其getter-setter方法

package com.journaldev.tinylog;

import org.tinylog.Logger;

public class Employee {

	private int id;
	private String name;

	public String getName() {
		Logger.debug("Returning employee name " + this.name);
		return name;
	}

	public void setName(String name) {
		Logger.info("Setting employee name " + name);
		this.name = name;
	}

	public int getId() {
		Logger.debug("Returning employee id " + this.id);
		return id;
	}

	public void setId(int id) {
		Logger.info("Setting employee id " + id);
		this.id = id;
	}
}

EmployeeService.java: A simple service class that provides a method to create an Employee object.

EmployeeService.java :一个简单的服务类,提供了一种创建Employee对象的方法。

package com.journaldev.tinylog;

import org.tinylog.Logger;

public class EmployeeService {

	public Employee createEmployee(int i, String n) {
		Logger.info("Creating Employee with ID = " + i + " and Name = " + n);
		Employee emp = new Employee();
		emp.setId(i);
		emp.setName(n);
		return emp;
	}
	
}

EmployeeMain.java: The main class to run our simple project.

EmployeeMain.java :运行我们的简单项目的主类。

package com.journaldev.tinylog;

import org.tinylog.Logger;

public class EmployeeMain {

	public static void main(String[] args) {		
		Logger.debug("Program Started");
		
		EmployeeService empService = new EmployeeService();

		Employee emp = empService.createEmployee(10, "Pankaj");

		System.out.println("Employee ID = " + emp.getId());
		System.out.println("Employee Name = " + emp.getName());

		Logger.debug("Program Finished");
	}
}

When we run the above program, it generates the following output. Note that we haven’t created the tinylog configuration file at this stage.

当我们运行上述程序时,它将生成以下输出。 请注意,我们目前尚未创建tinylog配置文件。

Tinylog Logging Example Output Console

TinyLog Logging Example Output Console

TinyLog日志记录示例输出控制台

TinyLog记录级别 (TinyLog Logging Levels)

Logger supports five logging levels – trace, debug, info, warn, and error. The default and the lowest priority level is “trace”. The highest priority level is “error”. We can set the logging level in the configuration file. The log messages of the level set and the higher priority will get logged.

记录器支持五个记录级别-跟踪,调试,信息,警告和错误。 默认值和最低优先级为“跟踪”。 最高优先级是“错误”。 我们可以在配置文件中设置日志记录级别。 设置级别和更高优先级的日志消息将被记录。

TinyLog配置文件 (TinyLog Configuration File)

TinyLog looks for the tinylog.properties file in the classpath to configure logging options. We usually create this file in the resources directory. Let’s create our first tinylog configuration file.

TinyLog在类路径中寻找tinylog.properties文件,以配置日志记录选项。 我们通常在资源目录中创建此文件。 让我们创建第一个tinylog配置文件。

tinylog.properties:

tinylog.properties

writer        = console
writer.format = {date: HH:mm:ss.SSS} {tag} {level}: {message}

When we run the main program again, the output is:

当我们再次运行主程序时,输出为:

12:22:47.073  DEBUG: Program Started
12:22:47.076  INFO: Creating Employee with ID = 10 and Name = Pankaj
12:22:47.076  INFO: Setting employee id 10
12:22:47.077  INFO: Setting employee name Pankaj
12:22:47.077  DEBUG: Returning employee id 10
Employee ID = 10
12:22:47.077  DEBUG: Returning employee name Pankaj
Employee Name = Pankaj
12:22:47.077  DEBUG: Program Finished

Notice that the log messages are following the format mentioned in the configuration file.

请注意,日志消息遵循配置文件中提到的格式。

TinyLog标签 (TinyLog Tags)

We can set Logger tag in the code using below code.

我们可以使用以下代码在代码中设置Logger标签。

Logger.tag("MAIN").debug("Program Started");

Logger.tag("MAIN").debug("Program Finished");

The updated log messages will contain the following lines.

更新后的日志消息将包含以下几行。

12:26:12.831 MAIN DEBUG: Program Started
...
12:26:12.835 MAIN DEBUG: Program Finished

We can set a writer tag to log messages having that tag, the other messages will be ignored by the writer.

我们可以设置一个writer标签来记录具有该标签的消息,其他消息将被writer忽略。

writer     = console
writer.tag = SYSTEM

We can ignore all the tags and only log untagged messages by setting the tag as “-“.

通过将标签设置为“-”,我们可以忽略所有标签,仅记录未加标签的消息。

writer     = console
writer.tag = -

TinyLog配置,可将消息记录到日志文件中 (TinyLog Configuration to log messages into a log file)

Here is a simple example to log messages into tinylog.txt file.

这是一个将消息记录到tinylog.txt文件中的简单示例。

writer       =  file
writer.file  = tinylog.txt
writer.level = info
writer.format = {date: HH:mm:ss.SSS} {tag} {level}: {message}

TinyLog supports reading environment variables too. For example, we can specify the log file to be generated at home directory using the following format.

TinyLog也支持读取环境变量。 例如,我们可以使用以下格式指定要在主目录中生成的日志文件。

writer.file = ${HOME}/tinylog.txt

We can also read system properties in the TinyLog configuration using the format #{key}.

我们还可以使用#{key}格式在TinyLog配置中读取系统属性。

writer.format = #{user.name}: {message}

滚动文件编写器配置 (Rolling File Writer Configuration)

writer       = rolling file
writer.file  = tinylog{count}.txt
writer.level = info
writer.format = {date: HH:mm:ss.SSS} {tag} {level}: {message}

扩展TingLog (Extending TingLog)

TinyLog is extendable. We can implement org.tinylog.writers.Writer interface and register it as a service. Similarly, we can implement org.tinylog.policies.Policy interface to create custom policies and register it. You can get more details about it here.

TinyLog是可扩展的。 我们可以实现org.tinylog.writers.Writer接口并将其注册为服务。 同样,我们可以实现org.tinylog.policies.Policy接口来创建自定义策略并进行注册。 您可以在此处获取有关它的更多详细信息。

GitHub Repository. GitHub存储库中签出最终项目。

翻译自: https://www.journaldev.com/31579/tinylog-lightweight-java-logging-framework-tutorial

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值