Инструменты пользователя

Инструменты сайта


works:programmer:java:logger-simple-made

Пример простенького логгера

import static java.lang.System.out;
import static java.lang.System.err;
import java.time.LocalDateTime;
 
enum LogLevel { Debug, Info, Warning, Error, Fatal }
 
final class Logger
{
 
    private static Logger instance = null;
 
    public void debug(String message, Object ...format) {
        logCommit(LogLevel.Info, message, format);
    }
 
    public void info(String message, Object ...format) {
        logCommit(LogLevel.Info, message, format);
    }
 
    public void log(String message, Object ...format) {
        logCommit(LogLevel.Info, message, format);
    }
 
    public void warning(String message, Object ...format) {
        logCommit(LogLevel.Warning, message, format);
    }
 
    public void error(String message, Object ...format) {
        logCommit(LogLevel.Error, message, format);
    }
 
    public void fatal(String message, Object ...format) {
        logCommit(LogLevel.Fatal, message, format);
        System.exit(1);
    }
 
    private void logCommit(LogLevel level, String message, Object ...format) {
        var now = LocalDateTime.now();
        var level_s = levelString(level);
        message = message.format(message, format);
        if (level == LogLevel.Warning || level == LogLevel.Error || level == LogLevel.Fatal) {
            err.println(now.toString() + " [" + level_s + "] " + message);
        } else {
            out.println(now.toString() + " [" + level_s + "] " + message);
        }
    }
 
    private static String levelString(LogLevel level) {
        switch (level) {
            case Debug: return "DEBG";
            case Info: return "INFO";
            case Warning: return "WARN";
            case Error: return "EROR";
            case Fatal: return "FATL";
            default  : return "????";
        }
    }
 
    public static Logger getInstance() {
        if (Logger.instance == null) {
            Logger.instance = new Logger();
        }
        return Logger.instance;
    }
 
}
 
class HelloWorld
{
 
    static private final Logger logger = Logger.getInstance();
 
    public static void main(String[] args) {
        logger.log("Hello, %s!", "World");
        logger.fatal("Stop with code 1");
        logger.log("Hello, %s!", "World");
    }
 
}
works/programmer/java/logger-simple-made.txt · Последнее изменение: 2023/08/03 10:40 — 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki