PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 25, 2022

[FIXED] How exactly is the logger a singleton and how are different log files created? Implemented my own logger for understanding

 October 25, 2022     design-patterns, java, log4j, oop, singleton     No comments   

Issue

In order to better understand how debug loggers work, I tried to implement my own logger in java. Shown in the code below. As far as I understand loggers are usually singletons. I want to use the same instance in different classes of my application. Each class where I use this logger will log to a different file. But that would mean that the singleton is being mutated by different objects. Wouldn't this cause inaccurately logging one classes debug output into a file that should be logged into by the other class. Since the same logger instance is shared across the entire app, how do different files get generated? Its the SAME instance being mutated in the application. So I decided to make the logFile location a final but then all classes would log to the same file. Could you shed some light on these curiosities?

Thank you in advance.

public class Logger {

    private final String logFile;
    private static Logger instance;

    private Logger(String logFile){
        this.logFile = logFile;
    }

    public Logger getInstance(String logFile){
        synchronized(Logger.class){
            if(instance==null){
                instance = new Logger(logFile);
            }
        }
        return instance;
    }

    public void write(String data) throws IOException{
        PrintWriter out = new PrintWriter (new BufferedWriter(new FileWriter(logFile)));
        out.write(data);
    }

}

Solution

IF you want understand the logger implementation you can read the source code of log4j. But in log4j loggers are not singleton, there are multiple instances, it uses repository and factory patterns.



Answered By - Mr_Thorynque
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing