All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.awidesky.guiUtil.TaskLogger Maven / Gradle / Ivy

/*
 * Copyright (c) 2023 Eugene Hong
 *
 * This software is distributed under license. Use of this software
 * implies agreement with all terms and conditions of the accompanying
 * software license.
 * Please refer to LICENSE
 * */

package io.github.awidesky.guiUtil;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.function.Consumer;

/**
 * An abstract Logger class for one-consumer, multi-provider model that manages each logs as "task"
 * (whose type is {@code Consumer})
 * 

log() method family call does not actually write the content to external log destination. * Instead, log content will be packed in a task. The content is actually written * when the task is executed. * *

TaskLogger provides abstract methods that queue({@code TaskLogger#queueLogTask(Consumer)}) * or run({@code TaskLogger#runLogTask(Consumer)}) the task. The queue(if exists) should be generated and managed in * another class or subclass. TaskLogger does not know or care about the queue. * */ public abstract class TaskLogger extends AbstractLogger { /** * Creates a task based logger. * */ public TaskLogger(boolean verbose, String prefix) { this.verbose = verbose; this.prefix = prefix; } /** * Queue a log task. * Implementation may queue given logTask to a worker thread. * */ protected abstract void queueLogTask(Consumer logTask); /** * Try to run a log task right away. * * @return true if succeed to run the logTask right away * */ protected abstract boolean runLogTask(Consumer logTask); /** * Logs a empty line without any prefix. * */ @Override public void newLine() { queueLogTask((logTo) -> { logTo.println(); }); } /** * Logs a String. * */ @Override public void log(String data) { queueLogTask(getLogTask(data)); } /** * Try to log a String right away. * * @return true if succeed to log a String right away. * */ public boolean logNow(String data) { return runLogTask(getLogTask(data)); } /** * Try to log an Exception right away. * * @return true if succeed to log an Exception right away. * */ public boolean logNow(Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); return logNow(sw.toString()); } /** * Try to log Objects(by calling {@code Object#toString()}) right away. * * @return true if succeed to log all Objects right away. * */ public boolean logNow(Object... objs) { return Arrays.stream(objs).map(Object::toString).allMatch(this::logNow); } /** * Prefix will printed only once even if the String is multiple line. * */ protected Consumer getLogTask(String data) { return (logTo) -> { logTo.println(getPrefix() + data); }; } /** Close the logger. */ @Override public abstract void close(); }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy