### Configure tinylog output format Source: https://github.com/tinylog-org/tinylog/wiki/Getting-Started This configuration snippet shows how to customize the output format for tinylog. It specifies the console writer and defines a custom format for the log messages, including time and log level. ```properties writer = console writer.format = {date: HH:mm:ss.SSS} {level}: {message} ``` -------------------------------- ### tinylog Placeholder Formatting Example Source: https://github.com/tinylog-org/tinylog/wiki/Configuration This example demonstrates how to configure tinylog's console writer to format log messages using various placeholders. It specifies the output format including log level, class and method names, and the log message. ```properties writer = console writer.format = {level}: {class}.{method}() {message} ``` -------------------------------- ### Log a message with tinylog Java Source: https://github.com/tinylog-org/tinylog/wiki/Getting-Started This Java code snippet demonstrates how to log an informational message using the tinylog logger. It requires the tinylog API and implementation JARs to be on the classpath. The output is a simple 'Hello World!' message. ```java import org.tinylog.Logger; public class Application { public static void main(String[] args) { Logger.info("Hello World!"); } } ``` -------------------------------- ### Configure Console Writer in Properties Source: https://context7.com/tinylog-org/tinylog/llms.txt Configure the console writer using a properties file. This example shows basic setup, forcing output to stdout or stderr, and setting custom thresholds for stderr. ```properties # Basic console writer (WARN/ERROR to stderr, others to stdout) writer = console writer.format = {date: HH:mm:ss.SSS} [{thread}] {level}: {message} # Force all output to stdout writer = console writer.stream = out writer.format = {level}: {message} # Force all output to stderr writer = console writer.stream = err # Custom threshold for stderr (ERROR and above to stderr) writer = console writer.stream = err@ERROR writer.format = {date: HH:mm:ss} {class}.{method}() {level}: {message} ``` -------------------------------- ### Configure Custom Writer with Format Pattern in Properties Source: https://github.com/tinylog-org/tinylog/wiki/Extending Configuration example for a custom writer using format patterns. It defines the writer and specifies a format string for log entry output. ```properties writer = system out writer.format = {level} :: {message} ``` -------------------------------- ### Advanced Message Formatting Example (Java) Source: https://context7.com/tinylog-org/tinylog/llms.txt Illustrates the use of the 'advanced' formatter in Java, employing {} placeholders for dynamic message content. The example shows how to log a username and IP address, with the output demonstrating the substituted values. ```java // Advanced formatter - {} placeholders Logger.info("User {} logged in from {}", username, ipAddress); // Output: 10:30:45 INFO: User admin logged in from 192.168.1.1 // Printf-style formatter - %s, %d placeholders ``` -------------------------------- ### Printf-style Message Formatting Example (Java) Source: https://context7.com/tinylog-org/tinylog/llms.txt Demonstrates logging with the 'printf' formatter in Java, using %s and %d placeholders. The example shows how to log a username and IP address, and the expected output with the substituted values. ```java Logger.info("User %s logged in from %s", username, ipAddress); // Output: 10:30:45 INFO: User admin logged in from 192.168.1.1 // Java MessageFormat style - {0}, {1} placeholders ``` -------------------------------- ### Java Custom Configuration Loader Example Source: https://github.com/tinylog-org/tinylog/wiki/Extending A Java implementation of the `ConfigurationLoader` interface for tinylog. This example shows how to load properties from a 'tinylog.properties' file located on the classpath. It requires the tinylog API and runtime dependencies. ```java package org.tinylog.example; import org.tinylog.configuration.ConfigurationLoader; import org.tinylog.runtime.RuntimeProvider; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class PropertiesConfigurationLoader implements ConfigurationLoader { @Override public Properties load() throws IOException { Properties properties = new Properties(); ClassLoader classLoader = RuntimeProvider.getClassLoader(); try (InputStream stream = classLoader.getResourceAsStream("tinylog.properties")) { if (stream != null) { properties.load(stream); } } return properties; } } ``` -------------------------------- ### Configure Custom Writer in Properties Source: https://github.com/tinylog-org/tinylog/wiki/Extending Example configuration for the custom 'system out' writer in tinylog.properties. It specifies the writer to use and sets a custom delimiter property. ```properties writer = system out writer.delimiter = :: ``` -------------------------------- ### Java MessageFormat Style Formatting Example (Java) Source: https://context7.com/tinylog-org/tinylog/llms.txt Shows how to log messages using Java's MessageFormat syntax ({0}, {1} placeholders) with tinylog. The example logs a username and IP address, illustrating the expected output after placeholder substitution. ```java Logger.info("User {0} logged in from {1}", username, ipAddress); // Output: 10:30:45 INFO: User admin logged in from 192.168.1.1 ``` -------------------------------- ### JSON Output Example in Java Source: https://context7.com/tinylog-org/tinylog/llms.txt An example demonstrating how to log structured data using tinylog's JSON writer in Java. It shows how key-value pairs are appended to the log message. ```java import org.tinylog.Logger; public class JsonLoggingExample { public static void main(String[] args) { Logger.info("User action", "userId", 12345, "action", "login"); // Output: {"timestamp":"2025-11-05T10:30:45.123Z","level":"INFO","message":"User action","userId":12345,"action":"login"} } } ``` -------------------------------- ### Configure Single Console Writer - Properties Source: https://github.com/tinylog-org/tinylog/wiki/Configuration Configuration for a single console writer in tinylog. Specifies the writer type, log level, and message format. This is a basic setup for console logging. ```properties writer = console writer.level = info writer.format = {level}: {class}.{method}() {message} ``` -------------------------------- ### Configure Multiple Writers (Console and File) - Properties Source: https://github.com/tinylog-org/tinylog/wiki/Configuration Configuration for using multiple writers simultaneously in tinylog. This example sets up both a console writer and a file writer with different log levels and file output settings. ```properties writer1 = console writer1.level = debug writer2 = file writer2.level = info writer2.file = log.txt ``` -------------------------------- ### Basic File Writer Configuration (Properties) Source: https://github.com/tinylog-org/tinylog/wiki/Configuration Configures tinylog to write all log entries with 'info' severity or higher to a file named 'log.txt'. This is a fundamental setup for file-based logging. ```properties writer = file writer.file = log.txt writer.level = info ``` -------------------------------- ### Programmatic Configuration (Java) Source: https://github.com/tinylog-org/tinylog/wiki/Configuration Illustrates how to configure tinylog programmatically using the `Configuration` class in Java. This method allows for dynamic configuration and is an alternative to properties files. ```java tinylog.Configuration.set("writer", "file"); tinylog.Configuration.set("writer.file", "programmatic.log"); tinylog.Configuration.set("writer.level", "trace"); ``` -------------------------------- ### Custom Configuration File Path (Command Line) Source: https://github.com/tinylog-org/tinylog/wiki/Configuration Demonstrates how to specify a custom configuration file path using a system property. This allows tinylog to load its settings from a non-default location. ```bash java -jar -Dtinylog.configuration=/tinylog/configuration.properties application.jar ``` -------------------------------- ### tinylog Custom Configuration Loader Service Registration Source: https://github.com/tinylog-org/tinylog/wiki/Extending Example of how to register a custom configuration loader with tinylog using the service loader mechanism. This involves creating a file in `META-INF/services` and listing the fully-qualified class name of the custom loader. ```text org.tinylog.example.PropertiesConfigurationLoader ``` -------------------------------- ### ProGuard Rules for tinylog Source: https://github.com/tinylog-org/tinylog/wiki/Configuration Essential ProGuard rules required for tinylog to function correctly with dynamic loading of providers, writers, and policies. Includes rules to suppress warnings and handle Android-specific optimizations. ```proguard -keepnames interface org.tinylog.** -keepnames class * implements org.tinylog.** -keepclassmembers class * implements org.tinylog.** { (...); } -dontwarn dalvik.system.VMStack -dontwarn java.lang.** -dontwarn javax.naming.** -dontwarn sun.reflect.Reflection ``` -------------------------------- ### Logging Exceptions in Java (Simple) Source: https://github.com/tinylog-org/tinylog/wiki/Logging Illustrates how to log exceptions directly in Java. The exception is passed as the first argument, and an optional message or arguments can follow. ```java Logger.trace(ex); Logger.debug(ex); Logger.info(ex); Logger.warn(ex); Logger.error(ex); ``` -------------------------------- ### Parameterized Logging in Java Source: https://github.com/tinylog-org/tinylog/wiki/Logging Shows how to log messages with placeholders '{}' for dynamic content in Java. Using placeholders is recommended over string concatenation for performance reasons. ```java Logger.trace("Divide {} by {}", a, b); Logger.debug("Divide {} by {}", a, b); Logger.info("Divide {} by {}", a, b); Logger.warn("Divide {} by {}", a, b); Logger.error("Divide {} by {}", a, b); ``` -------------------------------- ### Logging Exceptions with Message in Java Source: https://github.com/tinylog-org/tinylog/wiki/Logging Shows how to log an exception along with a formatted message and arguments in Java. The exception should always be the first argument. ```java Logger.trace(ex, "Cannot divide {} by {}", a, b); Logger.debug(ex, "Cannot divide {} by {}", a, b); Logger.info(ex, "Cannot divide {} by {}", a, b); Logger.warn(ex, "Cannot divide {} by {}", a, b); Logger.error(ex, "Cannot divide {} by {}", a, b); ``` -------------------------------- ### Commit Message Examples Source: https://github.com/tinylog-org/tinylog/blob/v2.8/contributing.md Examples of well-formatted commit messages for tinylog contributions. These messages follow a specific structure for the subject line and body to improve clarity and organization. ```git Add automatic module names and reuse them for bundles (#110) ``` ```git Add encoder runnable for compressing files by GZIP algorithm See #139 ``` ```git Run Checkstyle and Findbugs during verify phase This avoids side effects with instrumented classes from JaCoCo. ``` -------------------------------- ### Use System Properties in Log Format (Properties) Source: https://github.com/tinylog-org/tinylog/wiki/Configuration Allows placeholders for system properties within the log format string. The format is `#{key}`. If a property is not set, it remains as is. ```properties writer = console writer.format = #{user.name}: {message} ``` -------------------------------- ### Tagging Log Entries in Java Source: https://github.com/tinylog-org/tinylog/wiki/Logging Demonstrates how to use tags in tinylog for categorizing log entries in Java. Tags can be used for filtering logs or routing them to specific writers. Examples include basic tagging and creating reusable tagged logger instances. ```java Logger.tag("SYSTEM").trace("Hello World!"); Logger.tag("SYSTEM").debug("Hello World!"); Logger.tag("SYSTEM").info("Hello World!"); Logger.tag("SYSTEM").warn("Hello World!"); Logger.tag("SYSTEM").error("Hello World!"); ``` ```java TaggedLogger logger = Logger.tag("SYSTEM"); ``` ```java TaggedLogger logger = Logger.tags("FOO", "BAR", "BAZ"); ``` ```java TaggedLogger logger = Logger.tag(null); ``` -------------------------------- ### Logging Objects in Java Source: https://github.com/tinylog-org/tinylog/wiki/Logging Demonstrates logging objects directly in Java. tinylog optimizes this by only calling the `toString()` method when a log entry is actually generated, improving performance. ```java Logger.trace(LocalDate.now()); Logger.debug(LocalDate.now()); Logger.info(LocalDate.now()); Logger.warn(LocalDate.now()); Logger.error(LocalDate.now()); ``` -------------------------------- ### Register Custom tinylog Provider via META-INF/services Source: https://github.com/tinylog-org/tinylog/wiki/Extending This is a configuration file entry to register a custom logging provider with tinylog. It specifies the fully-qualified class name of the custom provider. This file should be placed in the `META-INF/services` directory. ```properties org.tinylog.example.SystemOutLoggingProvider ``` -------------------------------- ### Formatted Number Logging in Java Source: https://github.com/tinylog-org/tinylog/wiki/Logging Explains how to format numbers within log messages using DecimalFormat-compatible patterns in Java. This allows for consistent and readable numerical output. ```java Logger.trace("Income: {0.00} EUR", amount); Logger.debug("Income: {0.00} EUR", amount); Logger.info("Income: {0.00} EUR", amount); Logger.warn("Income: {0.00} EUR", amount); Logger.error("Income: {0.00} EUR", amount); ``` -------------------------------- ### Register Custom Throwable Filter as Service Source: https://github.com/tinylog-org/tinylog/wiki/Extending Registers a custom throwable filter by creating a service definition file. The file `META-INF/services/org.tinylog.throwable.ThrowableFilter` lists the fully-qualified class names of custom filters, one per line. ```plaintext com.example.PackageStripThrowableFilter ``` -------------------------------- ### Configure Rolling File Writer (Daily Rotation) Source: https://context7.com/tinylog-org/tinylog/llms.txt Configure a rolling file writer with daily rotation at a specified time. This example sets up rotation at midnight, retaining 30 backup files. ```properties writer = rolling file writer.file = logs/{date: yyyy-MM-dd}/application.log writer.policies = daily: 00:00 writer.backups = 30 writer.format = {date: HH:mm:ss} [{thread}] {level}: {message} ``` -------------------------------- ### Log Multi-line Message with Indentation (Java) Source: https://github.com/tinylog-org/tinylog/wiki/Configuration Demonstrates logging a multi-line message in Java, including lines with tabs, which will be formatted according to the `indent` configuration. ```java Logger.info("Multiple lines\nFirst line\n\tLine with tabs\nAnother line"); ``` -------------------------------- ### Register Custom Writer Service Source: https://github.com/tinylog-org/tinylog/wiki/Extending This snippet shows the content of the service registration file for a custom tinylog writer. It lists the fully-qualified class name of the custom writer. ```text org.tinylog.example.SystemOutWriter ``` -------------------------------- ### Implement Custom Writer Extending AbstractFormatPatternWriter in Java Source: https://github.com/tinylog-org/tinylog/wiki/Extending A custom writer that extends AbstractFormatPatternWriter, simplifying implementation by providing format pattern support. It overrides write, flush, and close methods. ```java package org.tinylog.example; import java.util.Map; import org.tinylog.core.LogEntry; import org.tinylog.writers.AbstractFormatPatternWriter; public class SystemOutWriter extends AbstractFormatPatternWriter { public SystemOutWriter(final Map properties) { super(properties); } @Override public void write(LogEntry logEntry) { System.out.println(render(logEntry)); } @Override public void flush() { System.out.flush(); } @Override public void close() { // System.out doesn't have to be closed } } ``` -------------------------------- ### Register Custom File Converter Source: https://github.com/tinylog-org/tinylog/wiki/Extending Registers the custom `CypherFileConverter` with tinylog by specifying its fully-qualified class name in the `META-INF/services/org.tinylog.converters.FileConverter` file. This allows tinylog to discover and use the converter at runtime. ```text org.tinylog.example.CypherFileConverter ``` -------------------------------- ### Environment Variable Placeholder (Properties) Source: https://github.com/tinylog-org/tinylog/wiki/Configuration Shows how to use environment variables within tinylog properties, such as specifying a log file path relative to the user's home directory. Placeholders are enclosed in `${}`. ```properties writer = file writer.file = ${HOME}/log.txt ``` -------------------------------- ### Plain Text Logging in Java Source: https://github.com/tinylog-org/tinylog/wiki/Logging Demonstrates logging messages at different severity levels (trace, debug, info, warn, error) using plain text in Java. This is the most straightforward way to log messages. ```java Logger.trace("Hello World!"); Logger.debug("Hello World!"); Logger.info("Hello World!"); Logger.warn("Hello World!"); Logger.error("Hello World!"); ``` -------------------------------- ### tinylog Service Registration for Custom Policy Source: https://github.com/tinylog-org/tinylog/wiki/Extending Registers the custom `RandomPolicy` with tinylog by creating a service definition file. This file, located at `META-INF/services/org.tinylog.policies.Policy`, lists the fully-qualified class names of all custom policies. ```text org.tinylog.example.RandomPolicy ``` -------------------------------- ### Configure Placeholder Fixed Size Source: https://github.com/tinylog-org/tinylog/wiki/Configuration Ensures a placeholder's value has a fixed size. It combines minimum and maximum size logic, padding with spaces or truncating from the beginning as needed to meet the exact size. ```properties writer = console writer.format = {thread|size=6}: {message} ``` -------------------------------- ### Programmatic JDBC Configuration in Java Source: https://context7.com/tinylog-org/tinylog/llms.txt Configures the JdbcWriter programmatically by providing a map of properties including URL, user, password, table name, and autocreation settings. This allows for dynamic setup of database logging. ```java import org.tinylog.writers.JdbcWriter; import java.util.HashMap; import java.util.Map; public class DatabaseLoggingSetup { public static void configureDatabaseLogging() { Map properties = new HashMap<>(); properties.put("url", "jdbc:mysql://localhost:3306/app_logs"); properties.put("user", "root"); properties.put("password", "password123"); properties.put("table", "logs"); properties.put("autocreate", "true"); JdbcWriter writer = new JdbcWriter(properties); // Writer is now configured and ready } } ``` -------------------------------- ### Environment Variable with Default Value (Properties) Source: https://github.com/tinylog-org/tinylog/wiki/Configuration Demonstrates how to provide a default value for an environment variable placeholder if the variable is not set. The default value is specified after a colon within the placeholder. ```properties writer = file writer.file = ${HOME:/tmp}/log.txt ``` -------------------------------- ### Configure File Writer with Options - Properties Source: https://github.com/tinylog-org/tinylog/wiki/Configuration Configuration for the tinylog file writer. Includes essential settings like file path, and optional parameters for log level, message format, character set, append mode, and buffering. ```properties writer = file writer.level = debug # optional writer.format = {level}: {message} # optional writer.file = log.txt # required, absolute or relative path writer.charset = UTF-8 # optional writer.append = true # optional, default: false writer.buffered = true # optional, default: false ``` -------------------------------- ### Configure Placeholder Minimum Size Source: https://github.com/tinylog-org/tinylog/wiki/Configuration Defines a minimum size for a placeholder. If the placeholder's value is shorter than the minimum size, spaces are appended to the right. If the value is equal or longer, no padding occurs. ```properties writer = console writer.format = {{level}:|min-size=8} {message} ``` -------------------------------- ### Lazy Logging with Lambdas in Kotlin Source: https://github.com/tinylog-org/tinylog/wiki/Logging Illustrates lazy logging in Kotlin using lambda expressions. Computations are deferred until a log entry is actually produced, optimizing performance for expensive operations. This includes logging with and without placeholders. ```kotlin Logger.trace { compute() } Logger.debug { compute() } Logger.info { compute() } Logger.warn { compute() } Logger.error { compute() } ``` ```kotlin Logger.trace("Expensive computation: {}", { compute() }) Logger.debug("Expensive computation: {}", { compute() }) Logger.info("Expensive computation: {}", { compute() }) Logger.warn("Expensive computation: {}", { compute() }) Logger.error("Expensive computation: {}", { compute() }) ``` -------------------------------- ### Configure Custom Throwable Filter in tinylog.properties Source: https://github.com/tinylog-org/tinylog/wiki/Extending Configures the usage of a custom throwable filter in tinylog.properties. The filter name is derived from the class name, with spaces inserted and 'Throwable Filter' removed. 'package strip' refers to `PackageStripThrowableFilter`. ```properties exception = package strip ``` -------------------------------- ### tinylog Configuration via Properties File Source: https://context7.com/tinylog-org/tinylog/llms.txt Shows an example of configuring tinylog's logging behavior using a properties file. It demonstrates setting the global log level and defining package-specific log levels for finer control over log output based on the origin of log messages. ```properties # Global log level (TRACE, DEBUG, INFO, WARN, ERROR, OFF) level = info # Package-specific levels level@com.example.database = debug level@com.example.security = warn level@org.springframework = error ``` -------------------------------- ### Set Writer-Specific Logging Level (Properties) Source: https://github.com/tinylog-org/tinylog/wiki/Configuration Limits the maximum severity level for a particular writer. This setting overrides the global level for the specified writer. Example: writer1 logs 'info' and above, writer2 logs 'warn' and above. ```properties writer1 = console writer1.level = debug writer2 = file writer2.file = log.txt writer2.level = info ``` -------------------------------- ### Manual Tinylog Shutdown (Java) Source: https://github.com/tinylog-org/tinylog/wiki/Configuration Provides an example of manually shutting down tinylog within a Java shutdown hook. This ensures that all log writers are properly closed when the application terminates, especially when automatic shutdown is disabled. ```java Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { ProviderRegistry.getLoggingProvider().shutdown(); } }); ``` -------------------------------- ### Java Application Example with tinylog Source: https://context7.com/tinylog-org/tinylog/llms.txt This complete Java application demonstrates end-to-end logging using tinylog. It showcases tagged loggers for different concerns (SECURITY, PERFORMANCE), thread context for request tracking, and dynamic log level configuration. ```java package com.example.app; import org.tinylog.Logger; import org.tinylog.TaggedLogger; import org.tinylog.ThreadContext; public class Application { private static final TaggedLogger securityLogger = Logger.tag("SECURITY"); private static final TaggedLogger performanceLogger = Logger.tag("PERFORMANCE"); public static void main(String[] args) { Logger.info("Application starting..."); try { // Initialize application initialize(); // Process requests for (int i = 0; i < 10; i++) { processRequest("REQ-" + i, "user" + (i % 3)); } Logger.info("Application completed successfully"); } catch (Exception e) { Logger.error(e, "Application failed"); System.exit(1); } } private static void initialize() { Logger.info("Initializing application"); Logger.debug("Loading configuration"); if (Logger.isTraceEnabled()) { Logger.trace("Configuration details: {}", loadConfiguration()); } Logger.info("Application initialized"); } private static void processRequest(String requestId, String userId) { long startTime = System.currentTimeMillis(); // Set thread context for all log entries ThreadContext.put("requestId", requestId); ThreadContext.put("userId", userId); try { Logger.info("Processing request"); securityLogger.debug("Validating user access"); // Simulate processing Thread.sleep(100); // Business logic with error handling if (Math.random() < 0.1) { throw new RuntimeException("Random processing error"); } Logger.info("Request processed successfully"); long duration = System.currentTimeMillis() - startTime; performanceLogger.info("Request duration: {}ms", duration); if (duration > 200) { performanceLogger.warn("Slow request detected: {}ms", duration); } } catch (Exception e) { Logger.error(e, "Request processing failed"); securityLogger.warn("Failed request for user: {}", userId); } finally { ThreadContext.clear(); } } private static String loadConfiguration() { // Expensive operation only called if TRACE is enabled return "config data here"; } } ``` -------------------------------- ### Configure tinylog Exception Handling Source: https://github.com/tinylog-org/tinylog/wiki/Configuration Configures tinylog to use specific exception filters, either globally or per writer. This example shows how to unpack exceptions and strip JDK internal stack trace elements, and also how to drop the cause of an exception for a console writer. ```properties exception = unpack, strip: jdk.internal writer = console writer.exception = drop cause ``` -------------------------------- ### Java Custom Rolling File Policy: RandomPolicy Source: https://github.com/tinylog-org/tinylog/wiki/Extending Implements the tinylog Policy interface to randomly decide whether to continue an existing log file or the current log file. It requires a constructor that accepts a string argument for seeding the random number generator. The `reset()` method is called when a new file is started. ```java package org.tinylog.example; import java.util.Random; import org.tinylog.policies.Policy; public class RandomPolicy implements Policy { private final Random random; public RandomPolicy(String argument) { if (argument == null || argument.isEmpty()) { random = new Random(); } else { random = new Random(Long.parseLong(argument)); } } @Override public boolean continueExistingFile(String path) { return random.nextBoolean(); } @Override public boolean continueCurrentFile(byte[] entry) { return random.nextBoolean(); } @Override public void reset() { // Nothing to do } } ``` -------------------------------- ### Basic Hello World Logging in Java using tinylog Source: https://github.com/tinylog-org/tinylog/blob/v2.8/readme.md This Java code snippet demonstrates the basic usage of tinylog for logging an informational message. It requires the tinylog library to be included as a dependency. The output will be a simple 'Hello world!' message. ```java import org.tinylog.Logger; public class Application { public static void main(String[] args) { Logger.info("Hello {}!", "world"); } } ``` -------------------------------- ### Implement Basic Custom Writer in Java Source: https://github.com/tinylog-org/tinylog/wiki/Extending A basic custom writer implementing the Writer interface. It takes properties from configuration, defines required log entry values, writes log entries to System.out, and handles flush/close operations. ```java package org.tinylog.example; import java.util.Collection; import java.util.EnumSet; import java.util.Map; import org.tinylog.core.LogEntry; import org.tinylog.core.LogEntryValue; import org.tinylog.writers.Writer; public class SystemOutWriter implements Writer { private final String delimiter; public SystemOutWriter(Map properties) { delimiter = properties.getOrDefault("delimiter", "-"); } @Override public Collection getRequiredLogEntryValues() { return EnumSet.of(LogEntryValue.LEVEL, LogEntryValue.MESSAGE); } @Override public void write(LogEntry logEntry) { System.out.println(logEntry.getLevel() + " " + delimiter + " " + logEntry.getMessage()); } @Override public void flush() { System.out.flush(); } @Override public void close() { // System.out doesn't have to be closed } } ``` -------------------------------- ### Idiomatic Kotlin Logging with Lambda Support Source: https://context7.com/tinylog-org/tinylog/llms.txt Illustrates various logging methods in Kotlin using tinylog's API, including simple logging, lazy evaluation with lambdas, formatted messages, exception logging, and tagged logging. ```kotlin import org.tinylog.kotlin.Logger class UserService { fun processUser(userId: Int) { // Simple logging Logger.trace("Processing user") Logger.debug("User ID: $userId") Logger.info("User processed successfully") Logger.warn("User cache is full") Logger.error("Database connection failed") // Lazy evaluation with lambda Logger.debug { "Expensive computation: ${calculateExpensiveValue()}" } // Formatted messages with placeholders Logger.info("User {} logged in from IP {}", userId, "192.168.1.1") // Exception logging try { riskyOperation() } catch (e: Exception) { Logger.error(e) Logger.error(e, "Operation failed") Logger.error(e, "Failed for user {}", userId) } // Tagged logging val securityLogger = Logger.tag("SECURITY") securityLogger.warn("Suspicious activity detected for user {}", userId) // Multiple tags val multiLogger = Logger.tags("AUDIT", "SECURITY") multiLogger.info("Critical security event") // Level checking if (Logger.isDebugEnabled()) { Logger.debug("Debug information: ${gatherDebugInfo()}") } } } ``` -------------------------------- ### Basic Logger API Usage in Java Source: https://context7.com/tinylog-org/tinylog/llms.txt Demonstrates the basic usage of the static Logger API in tinylog for different severity levels (TRACE, DEBUG, INFO, WARN, ERROR). It includes examples of simple message logging, checking log levels before expensive operations, formatted messages with placeholders, lazy evaluation for performance, and exception logging. ```java import org.tinylog.Logger; public class Application { public static void main(String[] args) { // Simple message logging Logger.trace("Entering application"); Logger.debug("Configuration loaded"); Logger.info("Application started successfully"); Logger.warn("Low memory detected"); Logger.error("Failed to connect to database"); // Check if level is enabled before expensive operations if (Logger.isDebugEnabled()) { Logger.debug("User data: " + expensiveToString()); } // Formatted messages with placeholders String user = "admin"; int attempts = 3; Logger.info("User {} logged in after {} attempts", user, attempts); // Lazy evaluation for performance Logger.debug(() -> "Expensive calculation: " + calculateComplexValue()); // Exception logging try { riskyOperation(); } catch (Exception e) { Logger.error(e); Logger.error(e, "Failed to perform operation"); Logger.error(e, "Operation failed for user {}", user); } } } ``` -------------------------------- ### Syslog Writer Configuration (TCP and UDP) Source: https://context7.com/tinylog-org/tinylog/llms.txt Demonstrates configuration for sending logs to a syslog server using either TCP or UDP protocols. It includes settings for host, port, protocol, facility, and custom formatting. ```properties # TCP syslog writer writer = syslog writer.host = syslog.example.com writer.port = 514 writer.protocol = tcp writer.facility = user writer.format = {level}: {message} ``` ```properties # UDP syslog writer with custom facility writer = syslog writer.host = 192.168.1.100 writer.port = 514 writer.protocol = udp writer.facility = local0 writer.hostname = app-server-01 writer.application = myapp writer.format = {date: ISO_INSTANT} {class}.{method} {message} ``` -------------------------------- ### Asynchronous Logging Example (Java) Source: https://context7.com/tinylog-org/tinylog/llms.txt Illustrates the usage of tinylog's asynchronous logging feature in Java. With 'writingthread=true', log messages are processed in a background thread, allowing the application to continue execution without waiting for I/O operations. The example demonstrates logging a large number of messages efficiently. ```java public class AsyncLoggingExample { public static void main(String[] args) { // With writingthread=true, logging is non-blocking for (int i = 0; i < 1000000; i++) { Logger.info("Message {}", i); // Returns immediately, writing happens in background } // autoshutdown=true ensures all logs are flushed on exit // Or manually call shutdown if needed // ProviderRegistry.getLoggingProvider().shutdown(); } } ``` -------------------------------- ### SLF4J Integration with tinylog Source: https://context7.com/tinylog-org/tinylog/llms.txt Bridges SLF4J API calls to the tinylog backend, allowing existing SLF4J code to use tinylog's features. Includes dependency information for Maven and demonstrates logging with MDC support and the fluent API. ```xml org.tinylog slf4j-tinylog 2.8.0 ``` ```java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; public class Slf4jExample { private static final Logger logger = LoggerFactory.getLogger(Slf4jExample.class); public void processRequest(String requestId) { // MDC support (mapped to tinylog ThreadContext) MDC.put("requestId", requestId); MDC.put("userId", "admin"); // Standard SLF4J logging logger.trace("Request processing started"); logger.debug("Processing request: {}", requestId); logger.info("Request {} processed successfully", requestId); logger.warn("Slow processing detected"); logger.error("Request processing failed"); // Exception logging try { processData(); } catch (Exception e) { logger.error("Processing failed for request {}", requestId, e); } // Fluent API (SLF4J 2.0+) logger.atInfo() .addKeyValue("requestId", requestId) .addKeyValue("duration", 1234) .log("Request completed"); // Clean up MDC MDC.clear(); } } ``` -------------------------------- ### Configure Rolling File Writer (Multiple Policies & Compression) Source: https://context7.com/tinylog-org/tinylog/llms.txt Configure a rolling file writer with multiple rotation policies (startup, daily, size) and compression. This advanced setup also defines a 'latest' log file and specifies buffering and character set. ```properties writer = rolling file writer.file = logs/app-{date: yyyy-MM-dd}_{count}.log writer.policies = startup, daily: 03:00, size: 50mb writer.backups = 100 writer.convert = gzip writer.latest = logs/current.log writer.format = {date: yyyy-MM-dd HH:mm:ss.SSS} {level} {class}:{line} - {message} writer.buffered = true writer.charset = UTF-8 writer.writingthread = true ``` -------------------------------- ### Set Locale for Formatting Source: https://github.com/tinylog-org/tinylog/wiki/Configuration Specifies the locale to be used for formatting numbers and dates within log messages. If not set, the default JVM locale is used. ```properties locale = en_US ``` -------------------------------- ### Implement Custom Logging Provider in Java for tinylog Source: https://github.com/tinylog-org/tinylog/wiki/Extending This Java code implements the `LoggingProvider` interface for tinylog. It outputs log entries with severity level INFO and higher to System.out. It includes implementations for all required methods like getContextProvider, getMinimumLevel, isEnabled, log, and shutdown. Dependencies include tinylog API artifacts. ```java package org.tinylog.example; import java.util.Locale; import org.tinylog.Level; import org.tinylog.provider.ContextProvider; import org.tinylog.provider.LoggingProvider; import org.tinylog.provider.MessageFormatter; import org.tinylog.provider.NopContextProvider; public class SystemOutLoggingProvider implements LoggingProvider { @Override public ContextProvider getContextProvider() { return new NopContextProvider(); } @Override public Level getMinimumLevel() { return Level.INFO; } @Override public Level getMinimumLevel(String tag) { return Level.INFO; } @Override public boolean isEnabled(int depth, String tag, Level level) { return level.ordinal() >= Level.INFO.ordinal(); } @Override public void log(int depth, String tag, Level level, Throwable exception, Object obj, Object... arguments) { log(exception, obj == null ? null : obj.toString(), arguments); } @Override public void log(String loggerClassName, String tag, Level level, Throwable exception, Object obj, Object... arguments) { log(exception, obj == null ? null : obj.toString(), arguments); } @Override public void shutdown() { // Nothing to do } private void log(Throwable exception, String message, Object[] arguments) { StringBuilder builder = new StringBuilder(); if (message != null) { builder.append(new MessageFormatter(Locale.ENGLISH).format(message, arguments)); } if (exception != null) { if (builder.length() > 0) builder.append(": "); builder.append(exception); } System.out.println(builder); } } ``` -------------------------------- ### Log with a Specific Tag (Java) Source: https://github.com/tinylog-org/tinylog/wiki/Configuration Logs a message with the specified tag using the tinylog Logger. This allows for conditional logging based on writer tag configurations. ```java Logger.tag("SYSTEM").info("Hello World!"); // Output Logger.info("Hello World!"); // Ignored ``` -------------------------------- ### tinylog Properties Configuration Source: https://context7.com/tinylog-org/tinylog/llms.txt This properties file configures tinylog for the application. It sets the global log level to 'info', a specific level for the 'com.example.app' package to 'debug', and defines a console writer with a custom format including request ID from the thread context. ```properties # tinylog.properties for the application level = info level@com.example.app = debug # Console output for development writer1 = console writer1.format = {date: HH:mm:ss.SSS} [{context: requestId}] {level}: {message} ``` -------------------------------- ### Log Exception with Indentation (Java) Source: https://github.com/tinylog-org/tinylog/wiki/Configuration Shows how exceptions, including their stack traces, are indented when logged. The general indentation rule applies to stack trace elements. ```java Logger.error(exception); ``` -------------------------------- ### Log4j 1.2 Compatibility API with tinylog Source: https://context7.com/tinylog-org/tinylog/llms.txt Provides a drop-in replacement for legacy Log4j 1.2 code by using tinylog's compatible API. Replace the Log4j dependency with tinylog's log4j1.2-api to redirect Log4j 1.2 calls to tinylog. Demonstrates standard logging levels and exception logging. ```java // Use tinylog's Log4j 1.2 compatible API import org.apache.log4j.Logger; public class LegacyApplication { private static final Logger logger = Logger.getLogger(LegacyApplication.class); public void legacyMethod() { // Log4j 1.2 API - backed by tinylog logger.trace("Trace message"); logger.debug("Debug message"); logger.info("Info message"); logger.warn("Warning message"); logger.error("Error message"); logger.fatal("Fatal message"); // -> tinylog ERROR // Exception logging try { riskyOperation(); } catch (Exception e) { logger.error("Operation failed", e); } // Level checking if (logger.isDebugEnabled()) { logger.debug("Expensive debug info: " + expensiveOperation()); } // No need to change existing Log4j 1.2 code // Just replace log4j dependency with tinylog log4j1.2-api } } ``` -------------------------------- ### Exception Filtering Demonstration (Java) Source: https://context7.com/tinylog-org/tinylog/llms.txt Provides a Java example demonstrating how different 'exception' settings in tinylog affect the logging of nested and chained exceptions. The code throws a series of exceptions to illustrate the impact of 'keep', 'strip', and 'drop cause' configurations. ```java public class ExceptionHandling { public void demonstrateExceptionFiltering() { try { throw new RuntimeException("Outer", new IllegalStateException("Middle", new NullPointerException("Inner"))); } catch (Exception e) { // With exception=keep: logs full chain (Outer -> Middle -> Inner) // With exception=strip: logs only Outer // With exception=drop cause: logs Outer without cause chain Logger.error(e, "Exception occurred"); } } } ``` -------------------------------- ### Log Untagged Entries (Java) Source: https://github.com/tinylog-org/tinylog/wiki/Configuration Logs a message without any tag. This entry will be processed by writers configured to accept untagged log entries (e.g., writer.tag = '-'). ```java Logger.tag("SYSTEM").info("Hello World!"); // Ignored Logger.info("Hello World!"); // Output ``` -------------------------------- ### Bind Writer to Untagged Log Entries (Properties) Source: https://github.com/tinylog-org/tinylog/wiki/Configuration Configures a writer to process only untagged log entries. This is achieved by setting the writer tag to a minus sign ('-'). ```properties writer = console writer.tag = - ``` -------------------------------- ### Bind Writer to a Single Tag (Properties) Source: https://github.com/tinylog-org/tinylog/wiki/Configuration Assigns a writer to a specific tag. Only log entries with this tag will be processed by this writer. Untagged entries and entries with other tags will be ignored. ```properties writer = console writer.tag = SYSTEM ``` -------------------------------- ### Conditional Number Formatting in Java Source: https://github.com/tinylog-org/tinylog/wiki/Logging Illustrates conditional formatting of numbers in log messages using ChoiceFormat-compatible patterns in Java. This enables dynamic messages based on numerical values. ```java Logger.trace("There {0#are no files|1#is one file|1