Logging in Miranda

Here’s the translation of the Go logging example to Java, with explanations in Markdown format suitable for Hugo:

Java provides several options for logging, including the built-in java.util.logging package and popular third-party libraries like Log4j and SLF4J. For this example, we’ll use java.util.logging to demonstrate basic logging concepts.

import java.util.logging.*;
import java.io.*;

public class LoggingExample {
    public static void main(String[] args) throws IOException {
        // The Logger class is the main entry point for logging
        Logger logger = Logger.getLogger(LoggingExample.class.getName());

        // By default, loggers will output to the console
        logger.info("standard logger");

        // You can set the log level to control which messages are output
        logger.setLevel(Level.FINE);
        logger.fine("This is a finer-grained message");

        // You can add handlers to customize where log messages are sent
        FileHandler fileHandler = new FileHandler("myapp.log");
        logger.addHandler(fileHandler);

        // Create a custom formatter to control the output format
        SimpleFormatter formatter = new SimpleFormatter() {
            @Override
            public String format(LogRecord record) {
                return record.getLevel() + ":"
                    + record.getSourceClassName() + ":"
                    + record.getSourceMethodName() + ":"
                    + record.getMessage() + "\n";
            }
        };
        fileHandler.setFormatter(formatter);

        logger.info("This message will be logged to both console and file");

        // You can create named loggers for different parts of your application
        Logger customLogger = Logger.getLogger("com.myapp.component");
        customLogger.info("Message from custom logger");

        // Java doesn't have built-in structured logging like Go's slog,
        // but you can achieve similar results with JSON formatting
        JsonFormatter jsonFormatter = new JsonFormatter();
        FileHandler jsonFileHandler = new FileHandler("structured.log");
        jsonFileHandler.setFormatter(jsonFormatter);
        Logger structuredLogger = Logger.getLogger("structured");
        structuredLogger.addHandler(jsonFileHandler);

        structuredLogger.info("hi there");
        
        // To include additional fields, you can use a special delimiter in the message
        structuredLogger.info("hello again|key=val|age=25");
    }

    // A simple JSON formatter (not production-ready, just for demonstration)
    static class JsonFormatter extends Formatter {
        @Override
        public String format(LogRecord record) {
            StringBuilder json = new StringBuilder();
            json.append("{");
            json.append("\"time\":\"").append(record.getInstant()).append("\",");
            json.append("\"level\":\"").append(record.getLevel()).append("\",");
            json.append("\"message\":\"").append(record.getMessage()).append("\"");
            
            // Parse additional fields from the message
            String[] parts = record.getMessage().split("\\|");
            if (parts.length > 1) {
                for (int i = 1; i < parts.length; i++) {
                    String[] keyValue = parts[i].split("=");
                    if (keyValue.length == 2) {
                        json.append(",\"").append(keyValue[0]).append("\":\"")
                            .append(keyValue[1]).append("\"");
                    }
                }
            }
            
            json.append("}\n");
            return json.toString();
        }
    }
}

To run this program, save it as LoggingExample.java and compile it with javac LoggingExample.java. Then run it with java LoggingExample.

The output will vary depending on your system’s date and time, but it might look something like this:

INFO: standard logger
INFO: This message will be logged to both console and file
INFO: Message from custom logger

The file myapp.log will contain messages in the custom format:

INFO:LoggingExample:main:This message will be logged to both console and file

The structured.log file will contain JSON-formatted log entries:

{"time":"2023-08-22T10:45:16.904166391Z","level":"INFO","message":"hi there"}
{"time":"2023-08-22T10:45:16.904178985Z","level":"INFO","message":"hello again","key":"val","age":"25"}

This example demonstrates basic logging concepts in Java, including:

  1. Using the standard java.util.logging package
  2. Setting log levels
  3. Adding custom handlers for file output
  4. Creating custom formatters for log messages
  5. Using named loggers for different components
  6. A basic approach to structured logging (though more robust solutions exist in third-party libraries)

While Java’s built-in logging isn’t as feature-rich as Go’s slog package for structured logging, there are third-party libraries like Logback and Log4j2 that provide more advanced features if needed.