log4j outputting to a file

Hi there;

I want to output my variable to a file, and I need to use log4j framework.

I wrote the following code but it seems it has no effect since the file is empty. (I created the file manually, not with the code).

   Logger logger = Logger.getLogger("com.foo");
        logger.setLevel(Level.INFO);
        logger.info(val);
        FileAppender fa = new FileAppender();
        fa.setFile("C:/log.txt");
        logger.addAppender(fa);

Open in new window


I also find an elegant way with,
http://www.mkyong.com/logging/log4j-log4j-properties-examples/

but I don't know where to put this properties code. Should I put it into my java source code or create a file and map it? (if so, how?), what should I do?

Regards.

P.S. it's not a web project but a simple java code with no main class to produce Jar (so I cannot output it to console).
LVL 12
jazzIIIloveAsked:
Who is Participating?
 
CEHJCommented:
One question: Is it possible to do this without properties file?
To do what?

As it happens, the best way to configure and use log4j is to use as little code as possible.
0
 
krakatoaCommented:
Here is what another expert put together. log4j to file

That might help. But if you need further assistance on it, then more help might be needed. ;)
0
 
CEHJCommented:
I wrote the following code but it seems it has no effect since the file is empty.
That's because you use the logger (line 3) before you add the FileAppender to it
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
jazzIIIloveAuthor Commented:
Hi CEHJ;

One question: Is it possible to do this without properties file?

Regards.
0
 
jazzIIIloveAuthor Commented:
Hi;

I mean should I also include the .properties file in the project? or is it OK without it?

Regards.
0
 
jazzIIIloveAuthor Commented:
ah, thanks I solved it.

 
		Logger logger = Logger.getLogger("com.foo");
        logger.setLevel(Level.INFO);
     
        FileAppender fa = new FileAppender();
        fa.setWriter(new OutputStreamWriter(new FileOutputStream(new File("C:\\log.txt"))));
        fa.setLayout(new PatternLayout("%-5p [%t]: %m%n"));
        
        logger.addAppender(fa);
        logger.info("aaaa");

Open in new window

0
 
CEHJCommented:
:)

But why would you have all that code in your own? It's not necessary...
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.