patternjavaMinor
Wrapper for Java logging
Viewed 0 times
loggingwrapperforjava
Problem
I am currently working on a new version of my application, and I just finished rebuilding the log part. It works well but I am skeptical about the choices I made. I am a student and I work alone in some side projects, and I am afraid of developing bad habits.
I use java.util.logging, because it is simple enough for what I need to do.
The logger will be used by several part of the application (but not at the same time). Each executable will have a logging file. All configurations are stored in
Main class :
```
public class MyLogger
{
public static Logger LOGGER = null; // Logger use by Spider, Cleaner, Checker
private static Handler logFile = null; // Logger file
/**
* Initialize logger before first use
*
* @param folderName sub-folder after the log folder
* @param fileName log file name (without extension)
*/
public static void initLogger(String folderName, String fileName)
{
if (MyLogger.LOGGER != null)
throw new IllegalStateException("Logger already instantiated");
MyLogger.LOGGER = Logger.getLogger(MyLogger.class.getName());
// Check if log is not disable
if (Settings.getProp().getLogLevel() != Level.OFF)
{
String folderPath = Settings.getProp().getLogPath() + folderName;
File dir = new File(folderPath);
// if the directory does not exist, create it (recursively)
if (!dir.exists())
{
try
{
dir.mkdirs();
}
catch (SecurityException e)
{
e.printStackTrace(); // Throw RunTime instead ?
}
}
try
{
// Open log file
MyLogger.logFile = new FileHandler(folderPath + File.separator + fileName + ".log", true);
MyLogger.logFile.setEncoding("UTF-8");
// Attache
I use java.util.logging, because it is simple enough for what I need to do.
The logger will be used by several part of the application (but not at the same time). Each executable will have a logging file. All configurations are stored in
Settings class.Main class :
```
public class MyLogger
{
public static Logger LOGGER = null; // Logger use by Spider, Cleaner, Checker
private static Handler logFile = null; // Logger file
/**
* Initialize logger before first use
*
* @param folderName sub-folder after the log folder
* @param fileName log file name (without extension)
*/
public static void initLogger(String folderName, String fileName)
{
if (MyLogger.LOGGER != null)
throw new IllegalStateException("Logger already instantiated");
MyLogger.LOGGER = Logger.getLogger(MyLogger.class.getName());
// Check if log is not disable
if (Settings.getProp().getLogLevel() != Level.OFF)
{
String folderPath = Settings.getProp().getLogPath() + folderName;
File dir = new File(folderPath);
// if the directory does not exist, create it (recursively)
if (!dir.exists())
{
try
{
dir.mkdirs();
}
catch (SecurityException e)
{
e.printStackTrace(); // Throw RunTime instead ?
}
}
try
{
// Open log file
MyLogger.logFile = new FileHandler(folderPath + File.separator + fileName + ".log", true);
MyLogger.logFile.setEncoding("UTF-8");
// Attache
Solution
1) Braces style
Putting opening curly braces on new lines is fine, though the big majority of Java developers don't do it and it wastes space.
Not putting curly braces around single line statements is dangerous and many people will discourage you from doing it!:
https://stackoverflow.com/questions/8020228/is-it-ok-if-i-omit-curly-braces-in-java
https://softwareengineering.stackexchange.com/questions/16528/single-statement-if-block-braces-or-no/16530
2) capitalized field names
Capitalized field names (LOGGER) are classically reserved for final constants, your LOGGER is not final. Meanwhile your DateFormat df should be capitalized.
3) Properly build paths
Use the File constructor to combine path parts:
https://stackoverflow.com/questions/412380/combine-paths-in-java
I guess making your ultimate File like
Pass the path of the file to your FileHandler constructor.
4) Throw RuntimeException on SecurityException
Your logger won't work. Something is wrong and your program shouldn't just silently ignore it! I'd prefer it to crash at that point: "Fix the logging or I won't work!"
5) SimpleDateFormat is not threadsafe!
Evil JRE developers want to secretly and unexpectedly mess up your date formatting:
https://stackoverflow.com/questions/6840803/simpledateformat-thread-safety
You should at least be aware of that if you plan to use multithreading.
6) Append cascade
Your append cascade is somewhat painful to read: It's hard for me to see exactly what you are combining.
I'd put every .append() on a new line.
7) Append cascade
Is there any advantage to calling
8) Seperate loggers for different classes, no direct access
Normally you create one logger for each class it's used in and put it in a static final field. That way it's easier to control logging and find out where the log entry comes from.
9) HH instead of H
You might want to use HH instead of H in your SimpleDateFormat, so your log entries are better aligned and more consistent.
Putting opening curly braces on new lines is fine, though the big majority of Java developers don't do it and it wastes space.
Not putting curly braces around single line statements is dangerous and many people will discourage you from doing it!:
https://stackoverflow.com/questions/8020228/is-it-ok-if-i-omit-curly-braces-in-java
https://softwareengineering.stackexchange.com/questions/16528/single-statement-if-block-braces-or-no/16530
2) capitalized field names
Capitalized field names (LOGGER) are classically reserved for final constants, your LOGGER is not final. Meanwhile your DateFormat df should be capitalized.
3) Properly build paths
Use the File constructor to combine path parts:
https://stackoverflow.com/questions/412380/combine-paths-in-java
I guess making your ultimate File like
File file = new File(folderName, fileName + ".log") and then calling file.getParentFile().mkdirs(); would be the most pleasant invocation.Pass the path of the file to your FileHandler constructor.
4) Throw RuntimeException on SecurityException
Your logger won't work. Something is wrong and your program shouldn't just silently ignore it! I'd prefer it to crash at that point: "Fix the logging or I won't work!"
5) SimpleDateFormat is not threadsafe!
Evil JRE developers want to secretly and unexpectedly mess up your date formatting:
https://stackoverflow.com/questions/6840803/simpledateformat-thread-safety
You should at least be aware of that if you plan to use multithreading.
6) Append cascade
Your append cascade is somewhat painful to read: It's hard for me to see exactly what you are combining.
I'd put every .append() on a new line.
7) Append cascade
Is there any advantage to calling
write(message.getBytes()); instead of println/print (message)? I have never seen that before. 8) Seperate loggers for different classes, no direct access
Normally you create one logger for each class it's used in and put it in a static final field. That way it's easier to control logging and find out where the log entry comes from.
9) HH instead of H
You might want to use HH instead of H in your SimpleDateFormat, so your log entries are better aligned and more consistent.
Context
StackExchange Code Review Q#138856, answer score: 2
Revisions (0)
No revisions yet.