alex.collins
alex.collins

Reputation: 611

Can I set the logging level within a Java method using log4j?

I've got one method in a class that is very verbose, and this makes the logs hard to read. I'd like to reduce its logging by just changing the level of that one method, leaving other methods in the same class unaltered. Is this possible?

Upvotes: 10

Views: 7908

Answers (4)

BigMike
BigMike

Reputation: 6863

It's possible. See my comment on OP.

The trick is creating a custom Level (less than TRACE) (as explained in here) and use that log level in very verbose methods.

Ofc in that method you won't user Logger shortcuts to logging methods, but you should resort to Logger.log(Level, Object) and Logger.log (Level, Object, Thowable) methods.

Upvotes: 1

Stephen C
Stephen C

Reputation: 718678

You cannot change the logging level on a per method basis. The "logger" is the finest level of granularity for control. Typically, there is a one-to-one relationship between logger instances and classes ... though that depends on how the application was coded.

If you can change the code, I recommend that you create special logger object for the noisy method so that you can control it independently of the other code that uses the existing logger. (Or maybe just change the method's logger calls.)

If you cannot change the code, you may have to resort to "hacks" such as post-processing the log files, or writing and configuring a custom Appender that suppresses the unwanted log messages.

Upvotes: 4

Sumit Desai
Sumit Desai

Reputation: 1760

I don't think it is posible directly to change logging method for only a method

Upvotes: 0

cjstehno
cjstehno

Reputation: 13984

You can change the level configuration for that class but not for specific methods in a class. The only way to do what you want would be to use a different logger inside that method and then configure it at a different level.

Hope this helps.

Upvotes: 8

Related Questions