Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - should I use constants for log messages? [closed]

Just a quick question about form.

I am logging various error messages and am wondering if I should create a new string for the message within the log call, or create a constant string within an interface I am using to store other string constants, and then just reference that. I was using a code analyzer code and it alluded to the latter saying it was better practice to create a string constant and reference it, even if it the string is only used once. I am just wondering if this is indeed the case?

Thanks in advance

like image 576
Pectus Excavatum Avatar asked Mar 12 '13 13:03

Pectus Excavatum


2 Answers

I'm not sure what analyzer tool you use or how you configured it but the advice seems invalid to me. The Java compiler will already create string constants for you (it usually will not allocate a new String instance when the code calls the log method), so what would be the point to do this work manually?

If you put the string constant into an interface, you can share them between classes but not in the way you think you would: The Java compiler will copy the constant's value into the code where it's being used (so the resulting byte code will not have a reference to the interface anymore!)

My suggestion: Turn off this misleading warning.

like image 150
Aaron Digulla Avatar answered Sep 28 '22 14:09

Aaron Digulla


Logging should be easy to add and remove; simply provide a very thin layer. And then there might be MessageFormats used, which are error prone/uncheckable when replaced by a constant name.

Also string constants are imported and then changes need no longer be detected, when the constant changes.

Also log strings are not very strict, informative on their own.

Better to mark those strings as non-internationalizable.

like image 30
Joop Eggen Avatar answered Sep 28 '22 16:09

Joop Eggen