-1

I need to periodically append text messages to a text file and I'm wanting to piggyback on log4j to make life easy. So I've created a "mylog.properties" file with a DailyRollingFileAppender -- nothing unusual -- and I've put that file in my src/java/resources directory. So now I'm ready to create a logger from this file and start logging with it, something like this:

class MyClass {
    private static final Logger myLog = getLoggerConfiguredFromPropertiesFile("mylog.properties");

    public void logSomething(String message) {
      myLog.info(message);
    }    
}

So what would be the logic for getLoggerConfiguredFromPropertiesFile?

Thanks, Alvaro

Alvaro Mendez
  • 134
  • 2
  • 13
  • Log4j uses global data. You can't have multiple instance of Log4j in an application (without using multiple classloaders and that's total overkill for this). Use Log4j the way it's intended to be used, or use something else. – Andreas Apr 12 '17 at 23:56
  • I see, so the problem is Log4j having static data. That's too bad because I could really use the DailyRollingFileAppender's features. – Alvaro Mendez Apr 13 '17 at 18:00

2 Answers2

0

Doing:

private static final Logger myLog = Logger.getLogger(MyClass.class)

should get the job done. log4j automatically looks for the closest log4j.properties to the class, and if you only have one in the project, it's that one. Also, call your file log4j.properties, not mylog.properties.

Ishnark
  • 661
  • 6
  • 14
  • Thanks but the solution I'm interested in is a local instance of a logger that I can configure with its own properties file and use only there. The rest of the app would use the global logger, as usual. Apparently it's not doable with Log4j :-(. – Alvaro Mendez Apr 13 '17 at 18:05
  • 1
    @AlvaroMendez It is doable, but not the way you say it. The one-and-only log4j configuration file (`log4j.properties`) can send all log entries from the `MyClass` logger to another file, so that when `MyClass` logs a message, it only gets logged in the alternate file (using `DailyRollingFileAppender`), and not in the main log file. You do that by setting "additivity" to false. See question: [Log4j config - different logs to different files](http://stackoverflow.com/q/23322602/5221149) – Andreas Apr 13 '17 at 19:48
0

I came up with a workaround where I'm using the regular logger:

private static final Logger myLog = LoggerFactory.getLogger(MyClass.class);

And in the log4j.properties, I configure a custom DailyRollingFileAppender that works just for my class, as explained here.

Community
  • 1
  • 1
Alvaro Mendez
  • 134
  • 2
  • 13