Java tinylog Tags to Different Log Files

Tags: tinylog

In this Java tinylog tutorial we show how to configure tinylog to allow the log entries write with different tags can be written to different log files.

Table of contents

  1. Add tinylog dependencies to Java project
  2. How to log entries with tags in tinylog
  3. How to configure different log files for different tags

Add tinylog dependencies to Java project

To use the tinylog library in the Gradle build project, add the following tinylog dependencies into the build.gradle file.

implementation group: 'org.tinylog', name: 'tinylog-api', version: '2.4.1'
implementation group: 'org.tinylog', name: 'tinylog-impl', version: '2.4.1'

To use the tinylog library in the Maven build project, add the following tinylog dependencies into the pom.xml file.

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

To have more information about the tinylog library you can visit the project home page at tinylog.org

How to log entries with tags in tinylog

The tinylog library provide API which allow logging entries with different tags as following Java example code.

TinyLogExample.java

import org.tinylog.Logger;

public class TinyLogExample {
    public static void main(String... args) {
        Logger.tag("DataAccess").info("Sample Message with data access tag");

        Logger.tag("WebApplication").info("Web application module message");
    }
}

How to configure different log files for different tags

At this step, we configure tinylog.properties file to allow logging the entries to different log files for different tags.

To do that we configure multiple writer, and need to ensure that each writer name is unique and must begin with “writer”.

src/main/resources/tinylog.properties

writerDataAccess            = file
writerDataAccess.tag        = DataAccess
writerDataAccess.file       = DataAccess.log
writerDataAccess.format     = {date: yyyy-MM-dd HH:mm:ss.SSS}{class}.{method}() {message}

writerWebApplication        = file
writerWebApplication.tag    = WebApplication
writerWebApplication.file   = WebApplication.log
writerWebApplication.format = {date: yyyy-MM-dd HH:mm:ss.SSS}{class}.{method}() {message}

Execute the Java application with above tinylog.properties config file we have 2 log files be written as below.

How to configure different log files for different tags

DataAccess.log

2022-04-07 01:36:55.397TinyLogExample.main() Sample Message with data access tag

WebApplication.log

2022-04-07 01:36:55.398TinyLogExample.main() Web application module message

Happy Coding 😊

Java tinylog Tutorial

Java tinylog Rolling File Writer

Java tinylog with Multiple Writers

Spring Boot logging with tinylog