0

import org.apache.log4j.BasicConfigurator;

import org.apache.log4j.Logger;

class MyClass {

private Logger log = Logger.getLogger(MyClass.class);

public void writeInConsol() {

  BasicConfigurator.configure();
  log.info("I write in consol!");  

}

public static void main(String[] args) {

  MyClass myClass = new MyClass();
  myClass.writeInConsol();  

}

}

  • this code write message-log in console, What must I add to this coda, that the code can write in any file by use library Log4j? (file.log or file.txt). Help me, Please :)

1 Answers1

0

If no configuration file could be located the DefaultConfiguration will be used. This will cause logging output to go to the console.

So you need log4j config, and FileAppender. See documentation here http://logging.apache.org/log4j/2.x/manual/appenders.html

it will be something like this

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyApp" packages="">
  <Appenders>
    <File name="MyFile" fileName="logs/app.log">
      <PatternLayout>
        <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
      </PatternLayout>
    </File>
  </Appenders>
  <Loggers>
    <Root level="error">
      <AppenderRef ref="MyFile"/>
    </Root>
  </Loggers>
</Configuration>
gohar.gasparyan
  • 233
  • 3
  • 8