Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 26

Thread: Creating a file logger using Singleton, factory, and abstract class

  1. #1
    Junior Member
    Join Date
    Dec 2013
    Posts
    25
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Creating a file logger using Singleton, factory, and abstract class

    Ok so here it goes, I have the format down I just don't know where and what the syntax is supposed to be for these classes. I have 5 classes:

    SimpleLogger - Abstract Class
    FileLogger - Singleton class
    LoggerFactory - Factory class
    Level - enum class
    LoggerException - self explanatory (catches errors)

    My problem is that I don't know how to code the SimpleLogger class :/

    for now this is what I have for the FileLogger

    if anyone could help it would be greatly appreciated

    public class FileLogger { 
     
    	private static FileLogger instance;
    	private SimpleLogger logger;
     
    	private FileLogger(){
    		logger = new SimpleLogger();
    	}
     
    	public static FileLogger getFileLogger(){
    		if (instance == null)
    		   instance = new FileLogger();
    		return instance;
    	}
     
     
    }


  2. #2
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    Quote Originally Posted by nickar1172 View Post
    My problem is that I don't know how to code the SimpleLogger class :/

    for now this is what I have for the FileLogger
    I don't known/I am not sure about what you've been precisely asked to do. So I can only guess. But from my point of view I imagine that FileLogger should be a normal, concrete, subclass of SimpleLogger and that LoggerFactory should have a method with SimpleLogger as return type but returning an instance of a concrete logger (that is only FileLogger at this moment).

    Please, clarify the architecture and final objectives.
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

  3. #3
    Junior Member
    Join Date
    Dec 2013
    Posts
    25
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    We start with a SimpleLogger which is an abstract class. It is a parent class of FileLogger, which is a concrete Singleton class that represents a single Logger. It also has all of the methods initialized. The LoggerFactory is called to create a Logger depending one what kind of Logger you want (we're only using File Loggers). Level class represents the enumerators/level that the created logger is set to. Finally, LoggerException is used to handle any errors with messages that are sent that are causing errors because they're not on a high enough logger level.


    When a message is logged, the logfile should contain the following information:  A timestamp  The log level of the message  The component that the program was in when the message is logged
     The message itself, or the stack trace of the Throwable (in the case of the second log method
    2
    The logfile should always be appended to, so that log messages from successive invocations of the logged software all appear in the file. This allows developers to compare log messages over time.

  4. #4
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,684
    Thanks
    25
    Thanked 333 Times in 309 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    Questions about your design:
    1. Why does FileLogger need to be a Singleton? Is it just a project requirement or something?
    2. Would the LoggerException occur if you, for example, tried to send an info message when the logger level was not high enough? Because that would be a poor design, since it would lead to lots of exceptions if the logger level was changed. Loggers generally ignore messages which are not within their logger level.
    3. Does SimpleLogger inherit from any of the already-existing java logging frameworks (this would probably be a good idea if not)?


    On to your primary question: how to design SimpleLogger. Since SimpleLogger is the an abstract parent class, you need to ask: what things will ALL the children need to be able to do? And then create abstract methods for each thing. For example, I would assume each logger would need methods like setLevel() and printMessage() (perhaps named differently). The way levels are set among the children probably won't be different, so that could be a method you implement in the SimpleLogger class. printMessage() however would be implemented differently, so that should be an abstract method.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  5. #5
    Junior Member
    Join Date
    Dec 2013
    Posts
    25
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    1. Yes it is a project requirement
    2. I'm not 100% positive the only thing I know is that we create our own exceptions so whatever is needed to be inputted in regards to error that are in the file logger gets implemented there, it really just depends on the design is what I'm trying to say
    3. I don't think so

    But as for the response to the primary question appreciate the help and I understand what you are saying but am a little confused on what to set the variable values to

  6. #6
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,684
    Thanks
    25
    Thanked 333 Times in 309 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    Ok, so since you are messing around with Singletons, you have to be aware of synchronization. This is critical for Singletons, as synchronization works to ensure thread safety (it's not perfect, but works well enough to prevent most problems). Research synchronization in Singletons to get a better idea. There should be tons of material on the internet about it.

    As for #3, if it is a school project, you probably want to avoid inheriting from java's existing logger package (I assume your professor wants you to write your own). In the real world however, the logger Level enum already exists (Level (Java Platform SE 6)) and your custom logger would inherit from java's existing logger functionality (Logger (Java Platform SE 6)), and you would probably even utilize java's existing file logging handling (FileHandler (Java Platform SE 6)). But that is a real-world implementation, verse school implementation (school implementation generally wants you to recreate the wheel).

    Which variable values? You'll need to give me an example of what you are confused about. Abstract classes CAN have class variables. As long as they are declared as public or protected, the variables can be directly referenced by subclasses.
    Now, there is a possible issue with synchronization when it comes to overriding abstract methods or inheriting variables. I don't know if you will face any issues here, but it is theoretically possible to have problems. I don't know if java has an issue with overriding an inherited abstract method and declaring it synchronized, or if synchronization of inherited variables will be honored in any way. I guess you'll find out, lol.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  7. #7
    Junior Member
    Join Date
    Dec 2013
    Posts
    25
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    I keep getting this error and I cant figure out why, the only thing is I cannot change the My Program class bc that was given by my instructor everything else is flexible

    public abstract class SimpleLogger {
     
    	protected Level level;
     
    	public void setLevel(Level l){
     
    	}	
    	public Level getLevel(){
    		return level;
     
    	}
    	public void log(Level logLevel, String component, String msg) throws LoggerException{
     
    	}
    	public void log(Level error, String component, Throwable t) throws LoggerException{
    	}
     
     
    public enum Level {
     
    	DEBUG(1), WARNING(2), SEVERE(3), INFO(4), ERROR(5);
     
    	private int level;
     
    	private Level(int level)
    	{
    		this.level = level;
    	}
    	public String toString(){
    		if(level ==1)
    			return "DEBUG";
    		else if(level ==2)
    			return "WARNING";
    		else if (level ==3)
    			return "SEVERE";
    		else if(level ==4)
    			return "INFO";
    		else if(level ==5)
    			return "ERROR";
    		return null;
    	}
    }
     
    public class MyProgram {
     
    	private SimpleLogger logger;
     
    	public static void main(String[] args) {
    	     try {
    			SimpleLogger logger = LoggerFactory.getLogger("File");
    			logger.setLevel(Level.INFO);
     
    			 logger.log(Level.INFO, "main", "system starting");
     
    			 try {
    				double res1 = doDivision(2,3);
    				 double res2 = doDivision(3,0);
    			} catch (Exception e) {
     
    				logger.log(Level.ERROR, "main", e);
    			}
    			 logger.log(Level.INFO,  "main", "system ending");
     
    		} catch (LoggerException e) {
     
    			e.printStackTrace();
    		}
     
    	}
     
    	private static double doDivision(int i, int j) {
    		{
    			double res=0;
    			 try {
    					SimpleLogger logger = LoggerFactory.getLogger("File");
     
    				//	 logger.initialize();
     
    					 logger.log(Level.INFO, "doDivision", "entering");
     
    				     if ( j == 0)
    				     {
    				    	 throw new IllegalArgumentException("Attempt to divide by  0");
    				     }
    				     else
    				     {
    				    	 res = i/j;
    				    	 logger.log(Level.INFO, "doDivision", "result is " + res);
    				     }
     
     
    				} catch (LoggerException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
     
    			 return res;
    		}
     
    	}
     
    }

  8. #8
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,684
    Thanks
    25
    Thanked 333 Times in 309 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    Notes:
    1. Your toString() method in your Level class is not needed. By default, enums print their name when you toString() them, so it already does that.
    2. Your setLevel() method isn't doing anything. It should say: level = l;
    3. If your log method should be abstract, instead of this:
    public void log(Level logLevel, String component, String msg) throws LoggerException {
     
    }
    write this:
    public abstract void log(Level logLevel, String component, String msg) throws LoggerException;

    4. What error are you getting?
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  9. #9
    Junior Member
    Join Date
    Dec 2013
    Posts
    25
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    I had a feeling that it had to be changed to abstract as well as the set method I just overlooked.

    This is the error code I keep getting:

    Exception in thread "main" java.lang.NullPointerException
    	at MyProgram.main(MyProgram.java:8)

    Indicating this line of code :
    logger.setLevel(Level.INFO);

    Every time I go to make changes I get errors change to .log

    also, I am having issues with:

    private SimpleLogger logger; 
    double res1 = doDivision(2,3);
    double res2 = doDivision(3,0);


    It keeps telling me there values are not used, I am not sure if this is because I have not set up the factory class yet

    --- Update ---

    I also, for:

    public enum Level {
     
    	DEBUG(1), WARNING(2), SEVERE(3), INFO(4), ERROR(5);
     
    	private int level;
     
    	private Level(int level)
    	{
    		this.level = level;
    	}
     
    }

    it is now telling me that level is not being used because I took out the toString(), is there anyway else I could implement it or should I just delete it

  10. #10
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,684
    Thanks
    25
    Thanked 333 Times in 309 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    For your last problem, you should probably have a getter for level. Just something that returns level. It is standard convention for enums with values.
    FYI: if your IDE (probably Eclipse, by the sound of it) tells you the value is not being used, that is a warning, not an error. There is nothing wrong with warnings and it will not change how your program runs. This warning just exists to tell you that it thinks you are doing unnecessary tasks. Specifically, the warning is telling you that you are never using the value of the variable in question to do anything.

    As for your null pointer, the only item on that line which can be null is the logger object. If you are getting the value of the logger object from your factory, your factory is probably not working properly.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  11. #11
    Junior Member
    Join Date
    Dec 2013
    Posts
    25
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    public class LoggerFactory {
     
     
    	public static SimpleLogger getLogger(String log) {
     
    	return new SimpleLogger(log);
    	}
     
    }

    Why can't SimpleLogger be instantiated?

  12. #12
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,684
    Thanks
    25
    Thanked 333 Times in 309 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    Because SimpleLogger is abstract. Abstract classes cannot be initialized.
    Instead, your factory method should check if the log String indicates a FileLogger, and if it does, return a new FileLogger() object.
    The FileLogger class is a concrete class (meaning it can be initialized, because it is not abstract and it is not an interface), so you can create a FileLogger object.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  13. #13
    Junior Member
    Join Date
    Dec 2013
    Posts
    25
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    but since FileLogger is a singleton doesnt that make the constructor private to something like

    return new FileLogger();

    cant be compiled?

  14. #14
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,684
    Thanks
    25
    Thanked 333 Times in 309 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    You should use FileLogger.getFileLogger() instead of the constructor.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  15. #15
    Junior Member
    Join Date
    Dec 2013
    Posts
    25
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    but then it would change:

    public class MyProgram {
     
    	private SimpleLogger logger;
     
    	public static void main(String[] args) {
    	     try {
    			SimpleLogger logger = LoggerFactory.getLogger("File");
    			logger.setLevel(Level.INFO);

    which is a problem

  16. #16
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,684
    Thanks
    25
    Thanked 333 Times in 309 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    Why would that change?
    FileLogger is-a SimpleLogger due to inheritance (FileLogger should extend SimpleLogger), so you can set a SimpleLogger variable with a FileLogger object, and when you call the setLevel() or log() methods on the SimpleLogger variable, it will automatically know to use the FileLogger's implemenation of the methods. That's java inheritance 101, but I know it can be very confusing to new developers.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  17. #17
    Junior Member
    Join Date
    Dec 2013
    Posts
    25
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    but then wouldn't the file logger be an abstract also if it extends SimpleLogger? so then the FileLogger class would be :
    public abstract class FileLogger extends SimpleLogger

  18. #18
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    I didn't read the whole thread, so generally speaking:
    No a class does not have to be abstract because it extends an abstract class. At some point the abstraction ends, and that point is the point where you want to create an instance of that class.

    public abstract class Candy...

    public abstract class PeanutCandy extends Candy...

    public class M&M extends PeanutCandy...
    public class MrGoodbar extends PeanutCandy...

  19. #19
    Junior Member
    Join Date
    Dec 2013
    Posts
    25
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    This is my new code, apparently my logger methods are "empty" and because of that I have no output. How do I go about fixing this??

    import java.util.*;
    import java.text.*;
    import java.io.*;
     
     
    public class FileLogger extends SimpleLogger {
     
    	private File logFile;
     
        private int logEntryNo = 0;
     
        private static FileLogger instance = null;
     
        public FileLogger(String logFilePath){
            logFile = new File(logFilePath);
            try{
                logFile.createNewFile();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
     
        public static FileLogger getInstance(){
            return instance;
        }
    	public void add(String data){
            DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
            Date date = new Date();
            String dateTime = dateFormat.format(date);
     
            try{
    			if (logFile.createNewFile()){
                    FileWriter fileWriter = new FileWriter(logFile);
                    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
                    bufferedWriter.write("[" + dateTime +  "]#" + ++logEntryNo + ": " + data);
                    bufferedWriter.newLine();
                    bufferedWriter.close();
                }
                else{
                    FileWriter fileWriter = new FileWriter(logFile,true);
                    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
                    bufferedWriter.write("[" + dateTime +  "]#" + ++logEntryNo + ": " + data);
                    bufferedWriter.newLine();
                    bufferedWriter.close();
                }
            }
            catch (IOException e) {
                e.printStackTrace();
            }
    }
     
    	@Override
    	public void log(Level logLevel, String component, String msg)
    			throws LoggerException {
    		// TODO Auto-generated method stub
     
    	}
     
    	@Override
    	public void log(Level error, String component, Throwable t)
    			throws LoggerException {
    		// TODO Auto-generated method stub
     
    	}
     
     
     
    	}
     
     
    public enum Level {
     
    	DEBUG(1), WARNING(2), SEVERE(3), INFO(4), ERROR(5);
    	private int level;
     
    	private Level(int level)
    	{
    		this.level = level;
    	}
    	public int getLevel(){
    		return level;
    	}
    }
     
     
    public class LoggerException extends Throwable {
     
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
     
    	public LoggerException(String name){
     
    		super("No attribute named \" " + name + "\" found");
     
    	}
     
    }
     
    public class LoggerFactory {
     
    	LoggerFactory factory = new LoggerFactory();
     
    	public static FileLogger getLogger(String string) {
    		if(string.equals("File"))
    		return new FileLogger(string);
    		return null;
    	}
     
     
     
     
    }
     
    public abstract class SimpleLogger {
     
    	protected Level level;
     
    	public void setLevel(Level l){
     
    		level = l;
     
    	}	
    	public Level getLevel(){
     
    		return level;
     
    	}
    	public abstract void log(Level logLevel, String component, String msg) throws LoggerException;
     
    	public abstract void log(Level error, String component, Throwable t) throws LoggerException;
     
    }
    public class MyProgram {
     
    	private SimpleLogger logger;
     
    	public static void main(String[] args) {
    	     try {
    			SimpleLogger logger = LoggerFactory.getLogger("File");
    			logger.setLevel(Level.INFO);
     
    			 logger.log(Level.INFO, "main", "system starting");
     
    			 try {
    				double res1 = doDivision(2,3);
    				 double res2 = doDivision(3,0);
    			} catch (Exception e) {
     
    				logger.log(Level.ERROR, "main", e);
    			}
    			 logger.log(Level.INFO,  "main", "system ending");
     
    		} catch (LoggerException e) {
     
    			e.printStackTrace();
    		}
     
    	}
     
    	private static double doDivision(int i, int j) {
    		{
    			double res=0;
    			 try {
    					SimpleLogger logger = LoggerFactory.getLogger("File");
     
    				//	 logger.initialize();
     
    					 logger.log(Level.INFO, "doDivision", "entering");
     
    				     if ( j == 0)
    				     {
    				    	 throw new IllegalArgumentException("Attempt to divide by  0");
    				     }
    				     else
    				     {
    				    	 res = i/j;
    				    	 logger.log(Level.INFO, "doDivision", "result is " + res);
    				     }
     
     
    				} catch (LoggerException e) {
     
    					e.printStackTrace();
    				}
     
    			 return res;
    		}
     
    	}
     
    }


    --- Update ---

    This is my new code, apparently my logger methods are "empty" and because of that I have no output. How do I go about fixing this??

    import java.util.*;
    import java.text.*;
    import java.io.*;
     
     
    public class FileLogger extends SimpleLogger {
     
    	private File logFile;
     
        private int logEntryNo = 0;
     
        private static FileLogger instance = null;
     
        public FileLogger(String logFilePath){
            logFile = new File(logFilePath);
            try{
                logFile.createNewFile();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
     
        public static FileLogger getInstance(){
            return instance;
        }
    	public void add(String data){
            DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
            Date date = new Date();
            String dateTime = dateFormat.format(date);
     
            try{
    			if (logFile.createNewFile()){
                    FileWriter fileWriter = new FileWriter(logFile);
                    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
                    bufferedWriter.write("[" + dateTime +  "]#" + ++logEntryNo + ": " + data);
                    bufferedWriter.newLine();
                    bufferedWriter.close();
                }
                else{
                    FileWriter fileWriter = new FileWriter(logFile,true);
                    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
                    bufferedWriter.write("[" + dateTime +  "]#" + ++logEntryNo + ": " + data);
                    bufferedWriter.newLine();
                    bufferedWriter.close();
                }
            }
            catch (IOException e) {
                e.printStackTrace();
            }
    }
     
    	@Override
    	public void log(Level logLevel, String component, String msg)
    			throws LoggerException {
    		// TODO Auto-generated method stub
     
    	}
     
    	@Override
    	public void log(Level error, String component, Throwable t)
    			throws LoggerException {
    		// TODO Auto-generated method stub
     
    	}
     
     
     
    	}
     
     
    public enum Level {
     
    	DEBUG(1), WARNING(2), SEVERE(3), INFO(4), ERROR(5);
    	private int level;
     
    	private Level(int level)
    	{
    		this.level = level;
    	}
    	public int getLevel(){
    		return level;
    	}
    }
     
     
    public class LoggerException extends Throwable {
     
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
     
    	public LoggerException(String name){
     
    		super("No attribute named \" " + name + "\" found");
     
    	}
     
    }
     
    public class LoggerFactory {
     
    	LoggerFactory factory = new LoggerFactory();
     
    	public static FileLogger getLogger(String string) {
    		if(string.equals("File"))
    		return new FileLogger(string);
    		return null;
    	}
     
     
     
     
    }
     
    public abstract class SimpleLogger {
     
    	protected Level level;
     
    	public void setLevel(Level l){
     
    		level = l;
     
    	}	
    	public Level getLevel(){
     
    		return level;
     
    	}
    	public abstract void log(Level logLevel, String component, String msg) throws LoggerException;
     
    	public abstract void log(Level error, String component, Throwable t) throws LoggerException;
     
    }
    public class MyProgram {
     
    	private SimpleLogger logger;
     
    	public static void main(String[] args) {
    	     try {
    			SimpleLogger logger = LoggerFactory.getLogger("File");
    			logger.setLevel(Level.INFO);
     
    			 logger.log(Level.INFO, "main", "system starting");
     
    			 try {
    				double res1 = doDivision(2,3);
    				 double res2 = doDivision(3,0);
    			} catch (Exception e) {
     
    				logger.log(Level.ERROR, "main", e);
    			}
    			 logger.log(Level.INFO,  "main", "system ending");
     
    		} catch (LoggerException e) {
     
    			e.printStackTrace();
    		}
     
    	}
     
    	private static double doDivision(int i, int j) {
    		{
    			double res=0;
    			 try {
    					SimpleLogger logger = LoggerFactory.getLogger("File");
     
    				//	 logger.initialize();
     
    					 logger.log(Level.INFO, "doDivision", "entering");
     
    				     if ( j == 0)
    				     {
    				    	 throw new IllegalArgumentException("Attempt to divide by  0");
    				     }
    				     else
    				     {
    				    	 res = i/j;
    				    	 logger.log(Level.INFO, "doDivision", "result is " + res);
    				     }
     
     
    				} catch (LoggerException e) {
     
    					e.printStackTrace();
    				}
     
    			 return res;
    		}
     
    	}
     
    }

  20. #20
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,684
    Thanks
    25
    Thanked 333 Times in 309 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    If FileLogger is supposed to be a singleton, the constructor should be private, and you are supposed to "construct" a FileLogger using the getInstance() method.
    Your getInstance() method earlier was correct. If you want to pass the singleton a file path, it should be:
    public static FileLogger getInstance(String logFilePath) {
    	if(instance==null)
    		instance = new FileLogger(logFilePath);
    	return instance;
    }
    Let me explain this method:
    The FileLogger instance variable is static. A static variable has the same value for all instances of the object. So if you set a static variable in a class, all instances of that class will have the same value for that variable. Even if you change the value of the static variable, all instances will also have their value changed (there are incorrect possessive pronouns in that statement, but I did that so it makes more sense to you).
    So, when you say: FileLogger.getInstance(), that method will look at the shared value of the static instance variable.
    The method is designed to say: if the static instance variable has never been set, create a new instance of the singleton and set the static variable. Then return the singleton instance.
    So, if this is the first time the singleton is being asked for, it will create the singleton and return it. Every other time the singleton is asked for, it will just return the already existing singleton object.
    Does that make sense?
    **Keep in mind that my above suggestion would NOT change the singleton if you tried to create a new one with a different file path. You would need a setter or something if you wanted to do that.**

    Your log methods are empty. I'm not sure what you want your log methods to do. I suppose they should create the log message and append it to the output file or something.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  21. #21
    Junior Member
    Join Date
    Dec 2013
    Posts
    25
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    yes but what log methods are you talking about that is where I am also lost

  22. #22
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,684
    Thanks
    25
    Thanked 333 Times in 309 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    FileLogger's log() methods.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  23. #23
    Junior Member
    Join Date
    Dec 2013
    Posts
    25
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    i don't know any log() methods that's the problem, I am a beginner in an advanced course, I thought the methods that I already have are the log methods that output but I guess I'm wayyyy off

    --- Update ---

    I apologize I'm just going nuts from the lack of sleep but by the log() methods you mean the:

    @Override
    	public void log(Level logLevel, String component, String msg)
    			throws LoggerException {
    		// TODO Auto-generated method stub
     
    	}
     
    	@Override
    	public void log(Level error, String component, Throwable t)
    			throws LoggerException{
    		// TODO Auto-generated method stub

    my issue is that I do not know what I am supposed to put inside there

  24. #24
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,684
    Thanks
    25
    Thanked 333 Times in 309 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    It's cool. It's exam week for me at college, so I understand stress right now, lol.

    My assumption is that you are wanting to log messages to the a file. So what you would need to do is create a new File object (file basics tutorial: Reading, Writing, and Creating Files (The Java™ Tutorials > Essential Classes > Basic I/O)) with the file path you provided the FileLogger. Once you have the new File object, you want to append the log message to the end of the file. And then you want to close the file when you are done. That last part is important. Leaving files open can lead to memory leaks. When you are done with an IO resource (such as files, streams, database connections, ect.), you should ALWAYS close them.
    Here is a messageboard post from StackOverflow where the responder explains it well: How to append text to an existing file in Java - Stack Overflow
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  25. #25
    Junior Member
    Join Date
    Dec 2013
    Posts
    25
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Creating a file logger using Singleton, factory, and abstract class

    how does this look?

    import java.util.*; 
    import java.text.*;
    import java.io.*;
     
     
    public class FileLogger extends SimpleLogger {
     
    	private File logFile;
        private static FileLogger instance;
     
     
    	public static FileLogger getInstance(String logFilePath){
    		if (instance == null)
    		   instance = new FileLogger(logFilePath);
    		return instance;
    	}
     
    	public FileLogger(String logFilePath){
            logFile = new File(logFilePath);
            try{
                logFile.createNewFile();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
     
     
    	@Override
    	public void log(Level logLevel, String component, String msg)
    			throws LoggerException {
     
    		DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
            Date date = new Date();
     
    		if(logLevel.compareTo(getLevel()) >=0)
    		try{
    			FileWriter out = new FileWriter(logFile,true);
    			String dateTime = dateFormat.format(date);
    			BufferedWriter bufferedWriter = new BufferedWriter(out);
    			bufferedWriter.append("\n" + dateTime + logLevel + component + msg + "");
            	bufferedWriter.newLine();
    			bufferedWriter.close();
    		}catch (IOException e) {
    			throw new LoggerException();
    		}
    	}
     
     
    	@Override
    	public void log(Level error, String component, Throwable t)
    			throws LoggerException{
    		DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
            Date date = new Date();
    		if(error.compareTo(getLevel()) >=0)
    			try{
    				FileWriter out = new FileWriter(logFile,true);
    				String dateTime = dateFormat.format(date);
    				BufferedWriter bufferedWriter = new BufferedWriter(out);
    				bufferedWriter.append("\n" + dateTime + error + component + t + "");
    	        	bufferedWriter.newLine();
    				bufferedWriter.close();
    	    }catch (IOException e) {
    	    throw new LoggerException();
    	    }
    	}
    }

    I am not 100% sure if it is meeting my requirements which are:

    When a message is logged, the logfile should contain the following information:  A timestamp  The log level of the message  The component that the program was in when the message is logged
     The message itself, or the stack trace of the Throwable (in the case of the second log method

    The logfile should always be appended to, so that log messages from successive invocations of the logged software all appear in the file. This allows developers to compare log messages over time.

    Message is only logged if it is at the appropriate log level.

Page 1 of 2 12 LastLast

Similar Threads

  1. Logger wirtes zero values to file
    By fannicola in forum What's Wrong With My Code?
    Replies: 2
    Last Post: June 29th, 2013, 06:21 PM
  2. Creating a Library, abstract class created issues. Also need GUI help.
    By rplee18 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: April 10th, 2013, 03:36 PM
  3. How to clone a singleton class?
    By Pratyush in forum What's Wrong With My Code?
    Replies: 7
    Last Post: February 4th, 2013, 01:27 AM
  4. Question on Singleton class
    By tcstcs in forum Java Theory & Questions
    Replies: 0
    Last Post: September 26th, 2012, 07:48 AM
  5. Creating a class file
    By ipatch in forum What's Wrong With My Code?
    Replies: 2
    Last Post: November 8th, 2009, 06:19 PM