Merge pull request #110 from informatik-ag-ngl/f/enhanced_logging

Logger hierarchy integration for EnvoyLog
This commit is contained in:
Kai S. K. Engelbart 2020-02-18 17:06:31 +01:00 committed by GitHub
commit fc7022834c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 66 additions and 46 deletions

View File

@ -24,7 +24,7 @@ public class Cache<T> implements Consumer<T>, Serializable {
private final Queue<T> elements = new LinkedList<>();
private transient Consumer<T> processor;
private static final Logger logger = EnvoyLog.getLogger(Cache.class.getSimpleName());
private static final Logger logger = EnvoyLog.getLogger(Cache.class);
private static final long serialVersionUID = 7343544675545545076L;
/**
@ -35,7 +35,7 @@ public class Cache<T> implements Consumer<T>, Serializable {
*/
@Override
public void accept(T element) {
logger.info(String.format("Adding element %s to cache", element));
logger.fine(String.format("Adding element %s to cache", element));
elements.offer(element);
}

View File

@ -46,7 +46,7 @@ public class Client implements Closeable {
// Configuration and logging
private static final Config config = Config.getInstance();
private static final Logger logger = EnvoyLog.getLogger(Client.class.getSimpleName());
private static final Logger logger = EnvoyLog.getLogger(Client.class);
/**
* Enters the online mode by acquiring a user ID from the server. As a
@ -77,8 +77,8 @@ public class Client implements Closeable {
receiver = new Receiver(socket.getInputStream());
// Register user creation processor, contact list processor and message cache
receiver.registerProcessor(User.class, sender -> { logger.info("Acquired user object " + sender); this.sender = sender; });
receiver.registerProcessor(Contacts.class, contacts -> { logger.info("Acquired contacts object " + contacts); this.contacts = contacts; });
receiver.registerProcessor(User.class, sender -> this.sender = sender);
receiver.registerProcessor(Contacts.class, contacts -> this.contacts = contacts);
receiver.registerProcessor(Message.class, receivedMessageCache);
receiver.registerProcessor(HandshakeRejectionEvent.class, evt -> { rejected = true; EventBus.getInstance().dispatch(evt); });
@ -88,7 +88,6 @@ public class Client implements Closeable {
new Thread(receiver).start();
// Write login credentials
logger.finest("Sending login credentials...");
SerializationUtils.writeBytesWithLength(credentials, socket.getOutputStream());
// Wait for a maximum of five seconds to acquire the sender object
@ -225,6 +224,7 @@ public class Client implements Closeable {
private void writeObject(Object obj) throws IOException {
checkOnline();
logger.fine("Sending object " + obj);
SerializationUtils.writeBytesWithLength(obj, socket.getOutputStream());
}

View File

@ -18,7 +18,7 @@ import envoy.event.MessageStatusChangeEvent;
*/
public class MessageStatusChangeEventProcessor implements Consumer<MessageStatusChangeEvent> {
private static final Logger logger = EnvoyLog.getLogger(MessageStatusChangeEventProcessor.class.getSimpleName());
private static final Logger logger = EnvoyLog.getLogger(MessageStatusChangeEventProcessor.class);
/**
* Dispatches a {@link MessageStatusChangeEvent} if the status is
@ -29,7 +29,7 @@ public class MessageStatusChangeEventProcessor implements Consumer<MessageStatus
*/
@Override
public void accept(MessageStatusChangeEvent evt) {
if (evt.get().ordinal() < MessageStatus.RECEIVED.ordinal()) logger.info("Received invalid message status change " + evt);
if (evt.get().ordinal() < MessageStatus.RECEIVED.ordinal()) logger.warning("Received invalid message status change " + evt);
else EventBus.getInstance().dispatch(evt);
}
}

View File

@ -13,13 +13,13 @@ import envoy.event.EventBus;
* Project: <strong>envoy-client</strong><br>
* File: <strong>ReceivedMessageProcessor.java</strong><br>
* Created: <strong>31.12.2019</strong><br>
*
*
* @author Kai S. K. Engelbart
* @since Envoy v0.3-alpha
*/
public class ReceivedMessageProcessor implements Consumer<Message> {
private static final Logger logger = EnvoyLog.getLogger(ReceivedMessageProcessor.class.getSimpleName());
private static final Logger logger = EnvoyLog.getLogger(ReceivedMessageProcessor.class);
@Override
public void accept(Message message) {

View File

@ -26,7 +26,7 @@ public class Receiver implements Runnable {
private final InputStream in;
private final Map<Class<?>, Consumer<?>> processors = new HashMap<>();
private static final Logger logger = EnvoyLog.getLogger(Receiver.class.getSimpleName());
private static final Logger logger = EnvoyLog.getLogger(Receiver.class);
/**
* Creates an instance of {@link Receiver}.
@ -51,13 +51,13 @@ public class Receiver implements Runnable {
try (ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(objBytes))) {
Object obj = oin.readObject();
logger.info("Received object " + obj);
logger.fine("Received object " + obj);
// Get appropriate processor
@SuppressWarnings("rawtypes")
Consumer processor = processors.get(obj.getClass());
if (processor == null)
logger.severe(String.format("The received object has the class %s for which no processor is defined.", obj.getClass()));
logger.warning(String.format("The received object has the class %s for which no processor is defined.", obj.getClass()));
else processor.accept(obj);
}
}

View File

@ -26,7 +26,7 @@ public class WriteProxy {
private final Client client;
private final LocalDb localDb;
private static final Logger logger = EnvoyLog.getLogger(WriteProxy.class.getSimpleName());
private static final Logger logger = EnvoyLog.getLogger(WriteProxy.class);
/**
* Initializes a write proxy using a client and a local database. The
@ -45,14 +45,14 @@ public class WriteProxy {
// Initialize cache processors for messages and message status change events
localDb.getMessageCache().setProcessor(msg -> {
try {
logger.info("Sending cached " + msg);
logger.finer("Sending cached " + msg);
client.sendMessage(msg);
} catch (IOException e) {
logger.log(Level.SEVERE, "Could not send cached message", e);
}
});
localDb.getStatusCache().setProcessor(evt -> {
logger.info("Sending cached " + evt);
logger.finer("Sending cached " + evt);
try {
client.sendEvent(evt);
} catch (IOException e) {

View File

@ -72,7 +72,7 @@ public class ChatWindow extends JFrame {
private final ComponentListModel<User> contactsModel = new ComponentListModel<>();
private final ComponentList<User> contactList = new ComponentList<>(contactRenderer);
private static final Logger logger = EnvoyLog.getLogger(ChatWindow.class.getSimpleName());
private static final Logger logger = EnvoyLog.getLogger(ChatWindow.class);
// GUI component spacing
private final static int space = 4;
@ -390,7 +390,6 @@ public class ChatWindow extends JFrame {
EventBus.getInstance().register(ContactSearchResult.class, evt -> {
contactsModel.clear();
final java.util.List<User> contacts = evt.get();
logger.info("Received contact search result " + contacts);
contacts.forEach(contactsModel::add);
revalidate();
repaint();

View File

@ -60,7 +60,7 @@ public class LoginDialog extends JDialog {
private final Cache<Message> receivedMessageCache;
private static final Config config = Config.getInstance();
private static final Logger logger = EnvoyLog.getLogger(LoginDialog.class.getSimpleName());
private static final Logger logger = EnvoyLog.getLogger(LoginDialog.class);
private static final long serialVersionUID = 352021600833907468L;
/**

View File

@ -34,7 +34,7 @@ public class Startup {
private static ChatWindow chatWindow;
private static final Logger logger = EnvoyLog.getLogger(Startup.class.getSimpleName());
private static final Logger logger = EnvoyLog.getLogger(Startup.class);
/**
* Loads the application by first loading the configuration, then acquiring a
@ -68,7 +68,8 @@ public class Startup {
System.exit(1);
}
// Set new logger levels loaded from config
// Setup logger for the envoy package
EnvoyLog.attach("envoy");
EnvoyLog.setFileLevelBarrier(config.getFileLevelBarrier());
EnvoyLog.setConsoleLevelBarrier(config.getConsoleLevelBarrier());

View File

@ -21,7 +21,7 @@ import envoy.client.util.EnvoyLog;
* Project: <strong>envoy-client</strong><br>
* File: <strong>GeneralSettingsPanel.java</strong><br>
* Created: <strong>21 Dec 2019</strong><br>
*
*
* @author Maximilian K&auml;fer
* @since Envoy v0.3-alpha
*/
@ -30,13 +30,13 @@ public class GeneralSettingsPanel extends SettingsPanel {
private Theme theme;
private static final String[] items = { "onCloseMode", "enterToSend" };
private static final Logger logger = EnvoyLog.getLogger(GeneralSettingsPanel.class.getSimpleName());
private static final Logger logger = EnvoyLog.getLogger(GeneralSettingsPanel.class);
private static final long serialVersionUID = -7470848775130754239L;
/**
* This is the constructor for the General class. Here the user can set general
* settings for the client.
*
*
* @param parent the {@link SettingsScreen} as a part of which this
* {@link SettingsPanel} is displayed
* @since Envoy v0.3-alpha
@ -89,5 +89,5 @@ public class GeneralSettingsPanel extends SettingsPanel {
}
@Override
public ActionListener getOkButtonAction() { return (evt) -> {}; }
public ActionListener getOkButtonAction() { return evt -> {}; }
}

View File

@ -47,7 +47,7 @@ public class SettingsScreen extends JDialog {
private SettingsPanel settingsPanel;
private static final Logger logger = EnvoyLog.getLogger(SettingsScreen.class.getSimpleName());
private static final Logger logger = EnvoyLog.getLogger(SettingsScreen.class);
/**
* Initializes the settings screen.

View File

@ -40,7 +40,7 @@ public class ThemeCustomizationPanel extends SettingsPanel {
private final Insets insets = new Insets(5, 5, 5, 5);
private static final Logger logger = EnvoyLog.getLogger(ThemeCustomizationPanel.class.getSimpleName());
private static final Logger logger = EnvoyLog.getLogger(ThemeCustomizationPanel.class);
private static final long serialVersionUID = -8697897390666456624L;
/**

View File

@ -2,11 +2,19 @@ package envoy.client.util;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.*;
import envoy.client.data.Config;
/**
* Configures the {@link java.util.logging} API to output the log into the
* console and a log file.<br>
* <br>
* Call the {@link EnvoyLog#attach(String)} method to configure a part of the
* logger hierarchy.<br>
* <br>
* Project: <strong>envoy-client</strong><br>
* File: <strong>EnvoyLogger.java</strong><br>
* Created: <strong>14 Dec 2019</strong><br>
@ -21,11 +29,13 @@ public class EnvoyLog {
private static StreamHandler consoleHandler;
static {
// Remove default console handler
LogManager.getLogManager().reset();
// Configure log file
File logFile = new File(Config.getInstance().getHomeDirectory(), "log/envoy_user.log");
File logFile = new File(Config.getInstance().getHomeDirectory(),
"log/envoy_user_" + new SimpleDateFormat("yyyy-MM-dd--hh-mm-mm").format(new Date()) + ".log");
logFile.getParentFile().mkdirs();
// Configure formatting
@ -47,38 +57,48 @@ public class EnvoyLog {
private EnvoyLog() {}
/**
* Creates a {@link Logger} with a specified name
* Configures all loggers that are contained within the hierarchy of a specific
* path to use the console and file handlers.
*
* @param name the name of the {@link Logger} to create
* @return the created {@link Logger}
* @since Envoy v0.2-alpha
* @param path the path to the loggers to configure
* @since Envoy Client v0.4-alpha
*/
public static Logger getLogger(String name) {
// Get a logger with the specified name
Logger logger = Logger.getLogger(name);
public static void attach(String path) {
// Get root logger
Logger logger = Logger.getLogger(path);
// Add handlers
if (fileHandler != null) logger.addHandler(fileHandler);
if (consoleHandler != null) logger.addHandler(consoleHandler);
logger.addHandler(consoleHandler);
return logger;
// Delegate logger level filtering to the handlers
logger.setLevel(Level.ALL);
}
/**
* @param fileLevelBarrier the severity below which logRecords will not be
* written to the log file. At or above they'll also be
* logged in a file. Can be written either in Digits
* from 0 - 1000 or with the according name of the level
* Creates a logger for a specified class, which output will be displayed inside
* the console and written to the log file.
*
* @param logClass the class in which the logger is used
* @return the created logger
* @since Envoy v0.2-alpha
*/
public static Logger getLogger(Class<?> logClass) {
return Logger.getLogger(logClass.getCanonicalName());
}
/**
* Defines the logger level required for a record to be written to the log file.
*
* @param fileLevelBarrier the log file level
* @since Envoy v0.2-alpha
*/
public static void setFileLevelBarrier(Level fileLevelBarrier) { if (fileHandler != null) fileHandler.setLevel(fileLevelBarrier); }
/**
* @param consoleLevelBarrier the severity below which logRecords will not be
* written to the console. At or above they'll also
* be logged in a file. Can be written either in
* digits from 0 - 1000 or with the according name of
* the level
* Defines the logger level required for a record to be written to the console.
*
* @param consoleLevelBarrier the console logger level
* @since Envoy v0.2-alpha
*/
public static void setConsoleLevelBarrier(Level consoleLevelBarrier) {