Repressing logging from another package - java

My code requests a DB to see if an object is present and then sets a value. The problem is even if the object is present, my logs get flooded with their logging code. How can I suppress these logging statements?

Yes! If you provide information about what logging system you use and other systematic information that could be helpful (like what db, where are the logs you want to suppress etc.) then someone will tell you how it can be done in your situation.

Related

Why printStackTrace is not recommended in ATG?

Why printStackTrace is not recommended to use in oracle ATG. If anyone knows please tell me.
Thanks in advance.
Avoiding the use printStackTrace is not just limited to ATG but should be applied to JAVA development in general. The SonarQube validation rules explains it as follow:
Throwable.printStackTrace(...) prints a throwable and its stack trace
to some stream. Loggers should be used instead to print throwables, as
they have many advantages:
Users are able to easily retrieve the logs.
The format of log messages is uniform and allow users to browse the logs easily
With the availability of logError you are able to easily spool your error messages, not only to the standard dynamo.log and error.log but you can also see them in context of the rest of your application logs.
There is another SO question touching the same topic available here.

Java conditional logging with the logging API

I understand that I can use
Logger.setLevel(<level here>);
To set the level of logging (turn it off, turn it on, etc). However, I'm not sure how I can conditionally log based on the log level the user specifies.
In essence, I have a class that uses the logging API. I wish to give the user of the class the power to configure the log level how they please. I've seen this done with log4j but not with the logging API.
Is there a best practice for this? Should I just have some function
setLogLevel()
that the user can pass a Level.INFO or whatever to? Or is there a better way?
Thank you!
I'm not sure, if understand this question correctly, but you shouldn't set the logging level from the code, which calls the logger. The idea behind logging is, that the developer logs all messages at the appropriate level. For example "Started to compute xyz" at DEBUG level, "New user have been set into DB" at INFO level and "Caught exception from..." at ERROR level. The logger will print the message only if it has the same or higher logging level. The logging level should be set according to environment, for example DEBUG for development and INFO for production, from outside the application.
Conditional logging is useful if the creation of the message is time consuming and you don't want to create the log message unless it will be really logged (check out this link). If you want to check, that the logger from the java.util.logging will actually log at given level, you can use this method.
However, I'm not sure how I can conditionally log based on the log level the user specifies.
Your question is unclear, but I think you are asking how log stuff depending on the log level that the user sets. The answer to that is that you just write your log statements normally; e.g.
logger.warning("Danger Will Robinson");
...
anotherLogger.info("It's good to be alive");
... and let the user specify what logging to capture using the logging configuration. Generally speaking the logging configuration is specified by a config file that is loaded at runtime, and can be altered by the user. It is also possible to create or alter the logging configuration programmatically, though presenting this functionality to the user via some kind of user-friendly UI is going to be something of a challenge.
In theory, it is also possible to a given log events at different levels depending on some condition. However, you are probably taking control away from the user by doing that.

Advantage in using Java Logger?

I want to log information to a file and want to know is there any advantage in using the Java Logger class versus my own personal method of logging?
I know using a logger I just add my own FileHandler to the logger. My personal method is just using a FileOutputStream.
Honestly your logger may be as good, it's pretty easy to put in log levels, filtering, etc.
The problem is when you start to put together code from 10 different groups each with their own logging. Some use System.out, some use some custom logger, some use log4j, ...
How do you parse or redirect the output? How do you filter all that output to just show your messages (For instance, filtering options in log4j won't prevent messages being sent straight to System.out).
It's a pretty big bulk change depending on which system you are moving from/to. Better just to use one very common one from the beginning and hope that it's the one everybody else on the project chooses.
The real question is: why would you bother writing your own logger when there are already existing libraries for doing that? Does your logger do something that the others don't? I kind of doubt it.
Standardization is another big issue - see Bill K's answer.
For most scenarios, a standard logging framework is the way to go. They are pretty flexible. But using your own implementation can also be a valid option, specially if we are not speaking of traditional logging (global debugging, problems, warning messages) but about specific informational meesages or accounting.
Among other factors, bear in mind that the standarization of logging allows third party libraries to cooperate. For example, if you have a standard web application using (say) Hibernate, and you have configured a standard Java logging lib, then you can not only log from your own code but also tell Hibernate to log debugging info to your log files (not necessarily the same files). That is very useful - almost a must.
If you code your own logging library with a plain FileOutputStream, you must decide -among other things- if you are going to keep the file opened, or reopen-append-close in each write - and you must take of synchronization and related issues. Nothing terribly complicated, though.
The logger gives to ability to define different levels of importance of the logged messages and the ability to use different sink for the output - the console, a file, etc.
Also it's easy to enable or disable only some type of message when using a logger - for example you don't want to see every debug message in production.
A logging framework allows you specify logging levels (e.g. log only critical messages, log only debug messages etc.). It also allows you to log to multiple destinations (e.g. to a file, to syslog etc.) and you can do this even after your application is fully built by just changing a config file and not changing any code. It can also format your logs easily depending on various parameters.
There are numerous other advantages since proper logging is a rather involved problem and these packages have been written to solve them. I think the important question, why would you not use them?
Well I would always prefer tested thing and approved by community over something which still need a lot of test. Logger allows you many things which will consume you some time to implement and to test the robustness of your solution. A big plus will be the know-how of the next person who will do something with your code, in case it will be your logger, normally it would take more time to learn how its working out, since there is much more examples and documentation for java.util.logger.
Like all others mention, there are more advantages to using a more common logging system over writing your own. To be honest, the Java util logging api is not nearly as extensive and configurable as other libraries you might find out there on the internet.
Bare in mind that rolling your own always has the disadvantage of being less tested and therefore more prone to break or skip some potentially crucial messages.
Personally I prefer using SLF4J since it allows me to plug in adapters for more commonly used logging frameworks and then let's me pick my own actual logging implementation, this solves most of the problems with different library writers preferring different logging frameworks. And if you consider yourself up for the task you could writer an implementation for SLF4J yourself ;)

What information to include at each log level? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Where/what level should logging code go?
Debug Levels
Is there a convention, a standard, or a widely used guide which will help with logging in Java? Specifically, what to include at each level (verbose, debug, ... etc.) rather than the actual mechanism of logging.
There are many guides out there of what to include at each log level, but none of them are specific; they're all vague, and this makes it hard to "follow orders".
Any tips would be appreciated.
It's subject to personal interpretation, but mine is (in order from finest to coursest):
Trace - The finest logging level. Can be used to log very specific information that is only relevant in a true debugging scenario, e.g., log every database access or every HTTP call etc.
Debug - Information to primary help you to debug your program. E.g., log every time a batching routine empties its batch or a new file is created on disk etc.
Info - General application flow, such as "Starting app", "connecting to db", "registering ...". In short, information which should help any observer understand what the application is doing in general.
Warn - Warns of errors that can be recovered. Such as failing to parse a date or using an unsafe routine. Note though that we should still try to obey the fail fast principle and not hide e.g., configuration errors using warning message, even though we a default value might be provided by the application.
Error - Denotes an often unrecoverable error. Such as failing to open a database connection.
Fatal/Critical Used to log an error the application cannot recover from, which might lead to an immediate program termination.
In the end it's up to you to define what suits you best. Personally, I run most production system with logging level of Info, where I'm mostly interested in following the applications main logic, and of course catch all warnings/errors.
Except for code cluttering, there is no such thing as too much logging. All logging which helps you reproduce or understand problems better are good logging. On a performance note, most logging systems (e.g., log4j) allows configuring which level to actually append to the physical log which is a great thing.
For what it's worth, we're using the following log levels:
DEBUG level messages give highly-detailed and/or specific information, only useful for tracking down problems.
INFORMATION messages give general information about what the system is doing. (e.g. processing file X)
WARNING messages warn the user about things which are not ideal, but should not affect the system. (e.g. configuration X missed out, using default value)
ERROR messages inform the user that something has gone wrong, but the system should be able to cope. (e.g. connection lost, but will try again)
CRITICAL messages inform the user when an un-recoverable error occurs. (i.e. I am about to abort the current task or crash)
I think the most important thing with log levels is to figure out a scheme, document it, and stick with it. Although making log level consistent between programs would be nice, as long as you've used common sense in defining your log levels, users will tolerate a certain amount of variance between programs.
Simple log what yuo think is important if you were to come back later and need to read the logs. This of course means that your Object.toStrings now need to be nice and readable and not a dump of crap thats impossible to read. This also means you need to do sensible things like quoting strings etc..

java.logging to String?

Hiho,
i'm trying to log errors with the help of java.logging
i want my logger to log everything to a log file and to a string or something(for html output(my program is a servlet))
I haven't found something like a StringHandler. Is there a possibility to do this?
greetings
The rationale behind a logging famework is to decouple your application code from logging - it sounds like you want to re-couple the two together. The biggest issue you will probably need to overcome is that all your log messages will be consolidated together, so you will see messages from separate requests in the same file.
If you want to be able to display to the user all the messages that your servlet has logged during the lifetime of their request you'll need to add an Handler as the first thing in your servlet, remove it in a finally block and then handle the messages its accumulated.
I'm not aware of any way in which you could reliably capture all relevent logging per request, as your servlet container will be executing code before you get to the point where you can intercept it, but as that sort of logging will probably deal with errors which would prevent you ever reporting anything back to the user, its probably a non-issue.
As some of the other answers intimate, logging though java.util.logging is rather basic, hence a number of other projects which provide logging, Logback being one of the best.
I think you can use the usual logger like log4j and a StringBuilder. That should do the trick.
You could try creating your own appender called StringAppender, as a subclass of WriterAppender with a StringWriter to log to.

Categories

Resources