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

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

There is a newer version: 1.3.3
Show newest version
/*
 * 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.text.DateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.stream.Collectors;


/**
 * An Abstract class for a {@code Logger} class with default implementations of general methods.
 * 
 * @author Eugene Hong
 * */
public abstract class AbstractLogger implements Logger {

	protected boolean verbose = false;
	protected DateFormat datePrefix = null;
	protected String prefix = null;

	
	/**
	 * Set date information prefix for this Logger instance.
	 * if argument is null, no date information prefix is appended.
	 * Date prefix is always appended very first of the line.
	 * */
	@Override
	public void setDatePrefix(DateFormat datePrefix) {
		this.datePrefix = datePrefix;
	}

	/**
	 * Set additional prefix for this Logger instance.
	 * if argument is null, no additional prefix is appended.
	 * The additional prefix is always appended after date prefix(if exists).
	 * 
	 * @see Logger#setDatePrefix(DateFormat)
	 * */
	@Override
	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}
	
	/**
	 * Generates prefix String(date prefix + additional prefix)
	 * */
	protected String getPrefix() {
		StringBuilder sb = new StringBuilder("");
		if(datePrefix != null) sb.append(datePrefix.format(new Date()));
		if(prefix != null) sb.append(prefix);
		return sb.toString();
	}
	
	/**
	 * Logs an Exception.
	 * */
	@Override
	public void log(Exception e) {
		StringWriter sw = new StringWriter();
		e.printStackTrace(new PrintWriter(sw));
		log(sw.toString());
	}
	/**
	 * Logs an array of Objects by calling {@code Object#toString()}.
	 * */
	@Override
	public void log(Object... objs) {
		log(Arrays.stream(objs).map(Object::toString).collect(Collectors.joining("\n")));
	}
	
	
	/**
	 * Set verbosity of this Logger object.
	 * */
	@Override
	public void setVerbose(boolean verbose) {
		this.verbose = verbose;
	}
	/**
	 * Set verbosity of this Logger object.
	 * */
	@Override
	public boolean isVerbose() {
		return verbose;
	}
	/**
	 * Log in verbose mode.
	 * If this.verbose is true, argument data is logged, otherwise it doesn't 
	 * */
	@Override
	public void logVerbose(String data) {
		if(verbose) log(data);
	}
	
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy