• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 482
  • Last Modified:

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).
0
jazzIIIlove
Asked:
jazzIIIlove
  • 3
  • 3
1 Solution
 
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
 
jazzIIIloveAuthor Commented:
Hi CEHJ;

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

Regards.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
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
 
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

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now