Merge pull request #58 from informatik-ag-ngl/f/logger

Advanced Logger with the ability to write logs to a file
This commit is contained in:
delvh 2019-12-20 12:52:13 +01:00 committed by GitHub
commit 16354ef392
10 changed files with 283 additions and 229 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
/target/ /target/
/localDB/ /localDB/
/log/
/themes.ser /themes.ser

View File

@ -18,6 +18,7 @@ import javax.xml.datatype.DatatypeFactory;
import envoy.client.event.EventBus; import envoy.client.event.EventBus;
import envoy.client.event.MessageCreationEvent; import envoy.client.event.MessageCreationEvent;
import envoy.client.util.EnvoyLog;
import envoy.exception.EnvoyException; import envoy.exception.EnvoyException;
import envoy.schema.Message; import envoy.schema.Message;
import envoy.schema.Message.Metadata.MessageState; import envoy.schema.Message.Metadata.MessageState;
@ -48,7 +49,7 @@ public class LocalDB {
private Sync sync = objectFactory.createSync(); private Sync sync = objectFactory.createSync();
private Sync readMessages = objectFactory.createSync(); private Sync readMessages = objectFactory.createSync();
private static final Logger logger = Logger.getLogger(LocalDB.class.getSimpleName()); private static final Logger logger = EnvoyLog.getLogger(LocalDB.class.getSimpleName());
/** /**
* Constructs an empty local database. To serialize any chats to the file * Constructs an empty local database. To serialize any chats to the file

View File

@ -88,7 +88,7 @@ public class Settings {
/** /**
* Updates the preferences when the save button is clicked. * Updates the preferences when the save button is clicked.
* *
* @throws IOException * @throws IOException if saving was not successful
* @since Envoy v0.2-alpha * @since Envoy v0.2-alpha
*/ */
public void save() throws IOException { public void save() throws IOException {
@ -105,7 +105,7 @@ public class Settings {
/** /**
* adds new theme to the theme map and sets current theme to the new theme. * adds new theme to the theme map and sets current theme to the new theme.
* *
* @param theme * @param theme the theme to add
* @since Envoy v0.2-alpha * @since Envoy v0.2-alpha
*/ */
public void addNewThemeToMap(Theme theme) { public void addNewThemeToMap(Theme theme) {
@ -114,7 +114,7 @@ public class Settings {
} }
/** /**
* @return {@link currentTheme} * @return the name of the current theme
* @since Envoy v0.2-alpha * @since Envoy v0.2-alpha
*/ */
public String getCurrentTheme() { return currentTheme; } public String getCurrentTheme() { return currentTheme; }
@ -122,7 +122,7 @@ public class Settings {
/** /**
* Sets the currentTheme * Sets the currentTheme
* *
* @param themeName * @param themeName the name of the new current theme
* @since Envoy v0.2-alpha * @since Envoy v0.2-alpha
*/ */
public void setCurrentTheme(String themeName) { currentTheme = themeName; } public void setCurrentTheme(String themeName) { currentTheme = themeName; }
@ -144,15 +144,13 @@ public class Settings {
public void setEnterToSend(boolean enterToSend) { this.enterToSend = enterToSend; } public void setEnterToSend(boolean enterToSend) { this.enterToSend = enterToSend; }
/** /**
* @return {@link themes} map * @return the map of all themes by name and colorContent
* @since Envoy v0.2-alpha * @since Envoy v0.2-alpha
*/ */
public Map<String, Theme> getThemes() { return themes; } public Map<String, Theme> getThemes() { return themes; }
/** /**
* Sets {@link themes} * @param themes the the the the
*
* @param themes
* @since Envoy v0.2-alpha * @since Envoy v0.2-alpha
*/ */
public void setThemes(Map<String, Theme> themes) { this.themes = themes; } public void setThemes(Map<String, Theme> themes) { this.themes = themes; }

View File

@ -6,6 +6,7 @@ package envoy.client.event;
* Created: <strong>04.12.2019</strong><br> * Created: <strong>04.12.2019</strong><br>
* *
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
* @param <T> the type of our Event
* @since Envoy v0.2-alpha * @since Envoy v0.2-alpha
*/ */
public interface Event<T> { public interface Event<T> {

View File

@ -30,8 +30,10 @@ import envoy.client.Client;
import envoy.client.Config; import envoy.client.Config;
import envoy.client.LocalDB; import envoy.client.LocalDB;
import envoy.client.Settings; import envoy.client.Settings;
import envoy.client.util.EnvoyLog;
import envoy.client.event.EventBus; import envoy.client.event.EventBus;
import envoy.client.event.ThemeChangeEvent; import envoy.client.event.ThemeChangeEvent;
import envoy.schema.Message; import envoy.schema.Message;
import envoy.schema.User; import envoy.schema.User;
@ -66,7 +68,7 @@ public class ChatWindow extends JFrame {
private static int space = 4; private static int space = 4;
private static final Logger logger = Logger.getLogger(ChatWindow.class.getSimpleName()); private static final Logger logger = EnvoyLog.getLogger(ChatWindow.class.getSimpleName());
public ChatWindow(Client client, LocalDB localDB) { public ChatWindow(Client client, LocalDB localDB) {
this.client = client; this.client = client;
@ -167,9 +169,9 @@ public class ChatWindow extends JFrame {
settingsButton.addActionListener((evt) -> { settingsButton.addActionListener((evt) -> {
try { try {
SettingsScreen.open(); new SettingsScreen().setVisible(true);
changeChatWindowColors(Settings.getInstance().getThemes().get(Settings.getInstance().getCurrentTheme()));
} catch (Exception e) { } catch (Exception e) {
SettingsScreen.open();
logger.log(Level.WARNING, "An error occured while opening the settings screen", e); logger.log(Level.WARNING, "An error occured while opening the settings screen", e);
e.printStackTrace(); e.printStackTrace();
} }
@ -237,6 +239,7 @@ public class ChatWindow extends JFrame {
/** /**
* Used to immediately reload the ChatWindow when settings were changed. * Used to immediately reload the ChatWindow when settings were changed.
* *
* @param theme the theme to change colors into
* @since Envoy v0.1-alpha * @since Envoy v0.1-alpha
*/ */
private void changeChatWindowColors(Theme theme) { private void changeChatWindowColors(Theme theme) {

View File

@ -11,6 +11,7 @@ import java.awt.Insets;
import java.awt.event.ItemEvent; import java.awt.event.ItemEvent;
import java.awt.event.ItemListener; import java.awt.event.ItemListener;
import java.util.Arrays; import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.swing.BoxLayout; import javax.swing.BoxLayout;
@ -25,8 +26,8 @@ import javax.swing.JPanel;
import javax.swing.JTextPane; import javax.swing.JTextPane;
import javax.swing.ListSelectionModel; import javax.swing.ListSelectionModel;
import envoy.client.LocalDB;
import envoy.client.Settings; import envoy.client.Settings;
import envoy.client.util.EnvoyLog;
import envoy.client.event.EventBus; import envoy.client.event.EventBus;
import envoy.client.event.ThemeChangeEvent; import envoy.client.event.ThemeChangeEvent;
@ -56,44 +57,23 @@ public class SettingsScreen extends JDialog {
private GridBagConstraints gbc_themeContent = new GridBagConstraints(); private GridBagConstraints gbc_themeContent = new GridBagConstraints();
private Theme selectedTheme = Settings.getInstance().getThemes().get(Settings.getInstance().getCurrentTheme());
private JButton createNewThemeButton = new JButton("Create New Theme"); private JButton createNewThemeButton = new JButton("Create New Theme");
private JPanel colorsPanel = new JPanel(); private JPanel colorsPanel = new JPanel();
private JButton okButton = new JButton("Save"); private JButton okButton = new JButton("Save");
private JButton cancelButton = new JButton("Cancel"); private JButton cancelButton = new JButton("Cancel");
private static int space = 5; private static int space = 5;
private Theme temporaryTheme; private Theme temporaryTheme, selectedTheme;
private static final Logger logger = Logger.getLogger(LocalDB.class.getSimpleName()); private static final Logger logger = EnvoyLog.getLogger(SettingsScreen.class.getSimpleName());
private static SettingsScreen settingsScreen;
// TODO: Add a JPanel with all the Information necessary:
// change (Picture,Username, Email, Password) and toggle(light/dark mode,
// "ctrl+enter"/"enter"
// to send a message directly)
/**
* Opens the settings screen.<br>
*
* @since Envoy v0.1-alpha
*/
public static void open() {
settingsScreen = new SettingsScreen();
settingsScreen.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
settingsScreen.setModal(true);
settingsScreen.setVisible(true);
}
/** /**
* Builds the settings screen. * Builds the settings screen.
* *
* @since Envoy v0.1-alpha * @since Envoy v0.1-alpha
*/ */
private SettingsScreen() { public SettingsScreen() {
logger.info(Settings.getInstance().getCurrentTheme()); logger.info(Settings.getInstance().getCurrentTheme());
setBounds(10, 10, 450, 650); setBounds(10, 10, 450, 650);
@ -122,7 +102,7 @@ public class SettingsScreen extends JDialog {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final JList<String> selectedOption = (JList<String>) listSelectionEvent.getSource(); final JList<String> selectedOption = (JList<String>) listSelectionEvent.getSource();
final String option = selectedOption.getSelectedValue(); final String option = selectedOption.getSelectedValue();
System.out.println(option); logger.log(Level.FINEST, option);
switch (option) { switch (option) {
case "Color Themes": case "Color Themes":
@ -173,7 +153,7 @@ public class SettingsScreen extends JDialog {
@Override @Override
public void itemStateChanged(ItemEvent e) { public void itemStateChanged(ItemEvent e) {
String selectedValue = (String) themes.getSelectedItem(); String selectedValue = (String) themes.getSelectedItem();
System.out.println(selectedValue); logger.log(Level.FINEST, selectedValue);
selectedTheme = Settings.getInstance().getThemes().get(selectedValue); selectedTheme = Settings.getInstance().getThemes().get(selectedValue);
} }
}); });
@ -229,7 +209,7 @@ public class SettingsScreen extends JDialog {
createNewThemeButton.addActionListener((evt) -> { createNewThemeButton.addActionListener((evt) -> {
try { try {
String s = JOptionPane.showInputDialog("Enter a name for the new theme"); String s = JOptionPane.showInputDialog("Enter a name for the new theme");
System.out.println(s); logger.log(Level.FINEST, s);
Settings.getInstance() Settings.getInstance()
.addNewThemeToMap(new Theme(s, temporaryTheme.getBackgroundColor(), temporaryTheme.getCellColor(), .addNewThemeToMap(new Theme(s, temporaryTheme.getBackgroundColor(), temporaryTheme.getCellColor(),
temporaryTheme.getInteractableForegroundColor(), temporaryTheme.getInteractableBackgroundColor(), temporaryTheme.getInteractableForegroundColor(), temporaryTheme.getInteractableBackgroundColor(),
@ -295,7 +275,7 @@ public class SettingsScreen extends JDialog {
Settings.getInstance().setEnterToSend(Settings.getInstance().isEnterToSend());// still temporary Settings.getInstance().setEnterToSend(Settings.getInstance().isEnterToSend());// still temporary
Settings.getInstance().setCurrentTheme(selectedTheme.getThemeName()); Settings.getInstance().setCurrentTheme(selectedTheme.getThemeName());
System.out.println(selectedTheme.getThemeName()); logger.log(Level.FINER, selectedTheme.getThemeName());
final Theme currentTheme = Settings.getInstance().getThemes().get(Settings.getInstance().getCurrentTheme()); final Theme currentTheme = Settings.getInstance().getThemes().get(Settings.getInstance().getCurrentTheme());
changeSettingsScreenColors(currentTheme); changeSettingsScreenColors(currentTheme);
@ -306,13 +286,18 @@ public class SettingsScreen extends JDialog {
revalidate(); revalidate();
repaint(); repaint();
} catch (Exception e) { } catch (Exception e) {
logger.info("Something went wrong when changing the setting"); logger.warning("Something went wrong when changing the setting");
settingsScreen.dispose(); JOptionPane.showMessageDialog(this, "Something went wrong when changing the setting");
dispose();
} }
}); });
} }
} }
changeSettingsScreenColors(Settings.getInstance().getThemes().get(Settings.getInstance().getCurrentTheme())); changeSettingsScreenColors(Settings.getInstance().getThemes().get(Settings.getInstance().getCurrentTheme()));
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModal(true);
} }
private void changeSettingsScreenColors(Theme theme) { private void changeSettingsScreenColors(Theme theme) {
@ -447,8 +432,7 @@ public class SettingsScreen extends JDialog {
try { try {
Color newColor = JColorChooser.showDialog(null, "Choose a color", color); Color newColor = JColorChooser.showDialog(null, "Choose a color", color);
if (newColor.getRGB() != color.getRGB()) { if (newColor.getRGB() != color.getRGB()) {
System.out.println("New Color"); logger.log(Level.FINEST, "New Color: " + String.valueOf(color.getRGB()));
System.out.println(color.getRGB());
// TODO: When Theme changed in same settings screen, color variable doesnt // TODO: When Theme changed in same settings screen, color variable doesnt
// update. // update.
temporaryTheme.setColor(yIndex, newColor); temporaryTheme.setColor(yIndex, newColor);

View File

@ -11,6 +11,7 @@ import javax.swing.JOptionPane;
import envoy.client.Client; import envoy.client.Client;
import envoy.client.Config; import envoy.client.Config;
import envoy.client.LocalDB; import envoy.client.LocalDB;
import envoy.client.util.EnvoyLog;
import envoy.exception.EnvoyException; import envoy.exception.EnvoyException;
import envoy.schema.User; import envoy.schema.User;
@ -28,11 +29,9 @@ import envoy.schema.User;
*/ */
public class Startup { public class Startup {
private static final Logger logger = Logger.getLogger(Startup.class.getSimpleName()); private static final Logger logger = EnvoyLog.getLogger(Startup.class.getSimpleName());
public static void main(String[] args) { public static void main(String[] args) {
logger.setLevel(Level.ALL);
Config config = Config.getInstance(); Config config = Config.getInstance();
try { try {
@ -81,10 +80,9 @@ public class Startup {
// Try entering offline mode // Try entering offline mode
localDB.loadUsers(); localDB.loadUsers();
User clientUser = localDB.getUsers().get(userName); User clientUser = localDB.getUsers().get(userName);
if(clientUser == null) if (clientUser == null) throw new EnvoyException("Could not enter offline mode: user name unknown");
throw new EnvoyException("Could not enter offline mode: user name unknown");
client.setSender(clientUser); client.setSender(clientUser);
} catch(Exception e2) { } catch (Exception e2) {
JOptionPane.showMessageDialog(null, e2.toString(), "Client error", JOptionPane.ERROR_MESSAGE); JOptionPane.showMessageDialog(null, e2.toString(), "Client error", JOptionPane.ERROR_MESSAGE);
System.exit(1); System.exit(1);
return; return;
@ -109,8 +107,7 @@ public class Startup {
logger.info("Client user ID: " + client.getSender().getID()); logger.info("Client user ID: " + client.getSender().getID());
// Save all users to the local database // Save all users to the local database
if(client.isOnline()) if (client.isOnline()) localDB.setUsers(client.getUsers());
localDB.setUsers(client.getUsers());
EventQueue.invokeLater(() -> { EventQueue.invokeLater(() -> {
try { try {

View File

@ -12,8 +12,8 @@ import envoy.schema.User;
import envoy.schema.User.UserStatus; import envoy.schema.User.UserStatus;
/** /**
* Defines how the {@code UserList} is displayed. * Defines how the {@code UserList} is displayed.<br>
* * <br>
* Project: <strong>envoy-client</strong><br> * Project: <strong>envoy-client</strong><br>
* File: <strong>UserListRenderer.java</strong><br> * File: <strong>UserListRenderer.java</strong><br>
* Created: <strong>12 Oct 2019</strong><br> * Created: <strong>12 Oct 2019</strong><br>
@ -26,7 +26,6 @@ public class UserListRenderer extends JLabel implements ListCellRenderer<User> {
private static final long serialVersionUID = 5164417379767181198L; private static final long serialVersionUID = 5164417379767181198L;
@SuppressWarnings("incomplete-switch")
@Override @Override
public Component getListCellRendererComponent(JList<? extends User> list, User value, int index, boolean isSelected, boolean cellHasFocus) { public Component getListCellRendererComponent(JList<? extends User> list, User value, int index, boolean isSelected, boolean cellHasFocus) {
if (isSelected) { if (isSelected) {

View File

@ -0,0 +1,70 @@
package envoy.client.util;
import java.io.File;
import java.io.IOException;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
/**
* Project: <strong>envoy-client</strong><br>
* File: <strong>EnvoyLogger.java</strong><br>
* Created: <strong>14 Dec 2019</strong><br>
*
* @author Leon Hofmeister
* @since Envoy v0.2-alpha
*/
public class EnvoyLog {
private static Level fileLevelBarrier = Level.CONFIG;
private EnvoyLog() {}
/**
* Creates a {@link Logger} with a specified name
* @param name the name of the {@link Logger} to create
* @return the created {@link Logger}
*/
public static Logger getLogger(String name) {
// Get a logger with the specified name
Logger logger = Logger.getLogger(name);
final String logPath = "log/envoy_user.log";
new File(logPath).getParentFile().mkdirs();
SimpleFormatter formatter = new SimpleFormatter();
try {
FileHandler fh = new FileHandler(logPath);
fh.setLevel(fileLevelBarrier);
fh.setFormatter(formatter);
logger.addHandler(fh);
} catch (SecurityException | IOException e) {
e.printStackTrace();
}
ConsoleHandler ch = new ConsoleHandler();
ch.setLevel(Level.FINEST);
ch.setFormatter(formatter);
logger.addHandler(ch);
return logger;
}
/**
* @return the fileLevelBarrier: The current barrier for writing logs to a file.
* @since Envoy v0.2-alpha
*/
public static Level getFileLevelBarrier() { return fileLevelBarrier; }
/**
* @param fileLevelBarrier the severity below which logRecords will be written
* only 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
* @since Envoy v0.2-alpha
*/
public static void setFileLevel(String fileLevelBarrier) { EnvoyLog.fileLevelBarrier = Level.parse(fileLevelBarrier); }
}