Usage of log4J levels - log4j

What is the best practice in using log4j levels while coding.
I mean when do we use INFO logging, when do we use DEBUG logging / ERROR logging etc.

In general, I follow these guidelines:
DEBUG : low level stuff. cache hit, cache miss, opening db connection
INFO : events that have business meaning - creating customer, charging cc...
WARN : could be a problem but doesn't stop your app. email address not found / invalid
ERROR : unexpected problem. couldn't open db connection. etc...

My baseline is always that INFO level is equivalent to System.out, and ERROR is equivalent to System.err.
DEBUG - Here you put all your tracing information, and specifically information that you don't want to see when your "comfort level" is system.out.
INFO - use this one for general messages, progress messages, for application related messages, but not for tracing.
WARN - provide alerts that something is wrong, perhaps unexpected, or that a workaround is used, but the application can still continue (socket timeout/retries, invalid user input, etc.).
ERROR - alerts about problems that prevent your app from continuing normally, e.g. database is down, missing bootstrap configuration.
A common mistake when writing libraries is to use ERROR level to indicate problems with the calling application (the code that uses the library) instead of indicating real errors within the library itself. See for example this hibernate bug -> http://opensource.atlassian.com/projects/hibernate/browse/HHH-3731
This is really annoying because messages from ERROR level are really difficult to suppress, so use them only to indicate problems with your own code.
All - I don't really use this one, it is practically the same as DEBUG or TRACE.

The best way to learn is by example. Read source of some open source things, like, oh, Tomcat or whatever is in your application area, and see what you see.

Despite this question is pretty old, this is really an important point that every developer should know, I highly recommend you to check the official page of Apache log4j.
Also I have found and useful image that describes this perfectly, log4jImage taken from supportweb.cs.bham.ac.uk/documentation/tutorials/docsystem/build/tutorials/log4j/log4j.html

TRACE:
The least level of log. Provides most detailed level of information.
DEBUG:
Log statement here are meant to help developers. Detailed state of your application.
INFO:
General business information. Progress and state of your application
WARN:
Warnings about unexpected events. These are not serious enough to abort your application.
ERROR :
Serious problems in your application.
Also having the right level of logging turned on in different environments is equally crucial.

Here are some guidelines I use:
TRACE: verbose logging for very low level debugging, things I would not normally need to see in a log unless there is some very obscure or unusual issue.
DEBUG: logging intended for developers' eyes only - contents of variables, results of comparisons, and other bits of information that help debug business logic.
INFO: high level information such as task X is now complete or some rule is satisfied and here is what I'm going to do next because of that rule.
WARN: there might be a problem but it's not severe enough to do any real harm to the flow of the business logic. For example maybe some variable is sometimes going to be null but we don't necessarily need it or we can work around it somehow. At the same time we still want to know about it just in case we're told later we need to find examples of it or investigate more carefully why it happens.
ERROR: A serious problem that definitely needs to be investigated further, but not serious enough to stop the application from accomplishing the task at hand.
FATAL: A very serious unexpected problem that we can't work around or recover from and may even prevent the application from doing something useful.

ERROR logging should always be on.
INFO + DEBUG should be on when tracking down problems/bugs.

To what others mentioned, I'd add TRACE and FATAL levels, the former is good for very verbose logging, the later is to indicate total show stopper. There are general guide lines on how you use levels, as mentioned by other above. However, the most important is how YOU will use it and how your USERS will interpret them. You need levels to focus on problems, so decide what is the problem in your case. Your users will hardly ever need trace or debug statements, but they will definitely want to nail problems and report them to you.

Related

What's stopping my command from terminating?

I'm writing a command line tool for installing Windows services using Node JS. After running a bunch of async operations, my tool should print a success message then quit. Sometimes however, it prints its success message and doesn't quit.
Is there a way to view what is queued on Node's internal event loop, so I can see what is preventing my tool from quitting?
The most typical culprit for me in CLI apps is event listeners that are keeping the process alive. I obviously can't say if that's relevant to you without seeing your code, though.
To answer your more general question, I don't believe there are any direct ways to view all outstanding tasks in the event loop (at least not from JS-land). You can, however, get pretty close with process._getActiveHandles() and process._getActiveRequests().
I really recommend you look up the documentation for them, though. Because you won't find any. They're undocumented. And they start with underscores. Use at your own peril. :)
try to use some tools to clarify the workflow - for example, the https://github.com/caolan/async#waterfall or https://github.com/caolan/async#eachseriesarr-iterator-callback
so, you don't lose the callback called and can catch any erros thrown while executing commands.
I think you also need to provide some code samples that leads to this errors.

CouchDB's crash-only design is for durability,why?

When I research on couchDB's durability , I find that couchDB use crash-only design to get durability.But I don't know what's the relationship between crash-only and durability.
By reading the Wiki of CouchDB
The CouchDB file layout and commitment system features all Atomic Consistent Isolated Durable (ACID) properties. On-disk, CouchDB never overwrites committed data or associated structures, ensuring the database file is always in a consistent state. This is a “crash-only" design where the CouchDB server does not go through a shut down process, it's simply terminated.
The durability is given by the fact that the DB is always in a consistant state, and that this is given by the fact that the structure of the DB is append-only (CouchDB never overwrites committed data or associated structures). This makes the error handling quite easy: it can crash instantaneously if there is an error.
I don't think that it's the "crash-only" that gives the durability. I think that the durability permits the use of "crash-only".
Doing the opposite would mean trying to be clever and add error-recovery code. That requires you to correctly identify the error and being correct in your assumptions about the recovery algorithm. Every part of the recovery process may introduce bugs. You may think the error is of a certain type when it's really another, or new unexpected errors may happen while you're already doing recovery.
Error recovery also means not only trying to redo the failed transaction. You must also find the original error, which is probably from some unexpected program or hardware state, and fix that state. Otherwise the same error might happen again.
Crash-only makes the probability of bugs lower, you don't need to find all the edge cases where something went wrong and your system administrator can easily be notified about the error (which may be a hardware error!). With this in mind crash-only may be a sound software design principle in some cases. At least it makes it easier to guarantee your data integrity.

How to see what started a thread in Xcode?

I have been asked to debug, and improve, a complex multithreaded app, written by someone I don't have access to, that uses concurrent queues (both GCD and NSOperationQueue). I don't have access to a plan of the multithreaded architecture, that's to say a high-level design document of what is supposed to happen when. I need to create such a plan in order to understand how the app works and what it's doing.
When running the code and debugging, I can see in Xcode's Debug Navigator the various threads that are running. Is there a way of identifying where in the source-code a particular thread was spawned? And is there a way of determining to which NSOperationQueue an NSOperation belongs?
For example, I can see in the Debug Navigator (or by using LLDB's "thread backtrace" command) a thread's stacktrace, but the 'earliest' user code I can view is the overridden (NSOperation*) start method - stepping back earlier in the stack than that just shows the assembly instructions for the framework that invokes that method (e.g. __block_global_6, _dispatch_call_block_and_release and so on).
I've investigated and sought various debugging methods but without success. The nearest I got was the idea of method swizzling, but I don't think that's going to work for, say, queued NSOperation threads. Forgive my vagueness please: I'm aware that having looked as hard as I have, I'm probably asking the wrong question, and probably therefore haven't formed the question quite clearly in my own mind, but I'm asking the community for help!
Thanks
The best I can think of is to put breakpoints on dispatch_async, -[NSOperation init], -[NSOperationQueue addOperation:] and so on. You could configure those breakpoints to log their stacktrace, possibly some other info (like the block's address for dispatch_async, or the address of the queue and operation for addOperation:), and then continue running. You could then look though the logs when you're curious where a particular block came from and see what was invoked and from where. (It would still take some detective work.)
You could also accomplish something similar with dtrace if the breakpoints method is too slow.

How can I handle an access violation in Visual Studio C++?

Usually an access violation terminates the program and I cannot catch a Win32 exception using try and catch. Is there a way I can keep my program running, even in case of an access violation? Preferably I would like to handle the exception and show to the user an access violation occurred.
EDIT: I want my program to be really robust, even against programming errors. The thing I really want to avoid is a program termination even at the cost of some corrupted state.
In Windows, this is called Structured Exception Handling (SEH). For details, see here:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms680657%28v=vs.85%29.aspx
In effect, you can register to get a callback when an exception happens. You can't do this to every exception for obvious reasons.
Using SEH, you can detect a lot of exceptions, access violations included, but not all (e.g. double stack fault). Even with the exceptions that are detectable, there is no way to ensure 100% stability after the exception. However, it may be enough to inform the user, log the error, send a message back to the server, and gracefully exit.
I will start by saying that your question contains a contradiction:
EDIT: I want my program to be really robust, ... The thing I really want to avoid is a program termination even at the cost of some corrupted state.
A program that keeps on limpin' in case of corrupted state isn't robust, it's a liability.
Second, an opinion of sorts. Regarding:
EDIT: I want my program to be really robust, even against programming errors. ...
When, by programming errors you mean all bugs, then this is impossible.
If by programming errors you mean: "programmer misused some API and I want error messages instead of a crash, then write all code with double checks built in: For example, always check all pointers for NULL before usage, even if "they cannot be NULL if the programmer didn't make a mistake", etc. (Oh, you might also consider not using C++ ;-)
But IMHO, some amount of program-crashing-no-matter-what bugs will have to be accepted in any C++ application. (Unless it's trivial or you test the hell out of it for military or medical use (even then ...).)
Others already mentioned SEH -- it's a "simple" matter of __try / __catch.
Maybe instead of trying to catch bugs inside the program, you could try to become friends with Windows Error Reporting (WER) -- I never pulled this, but as far as I understand, you can completely customize it via the OutOfProcessException... callback functions.

VS2012 - Why is my main UI thread showing green debugging statements?

Edit : If you're seeing this same problem (and you're accustomed to NOT seeing this under VS2010) please comment below so I know it's not just me - but be sure to check Han's answer to make sure none of those scenarios appear...
I've been updating my app to run with .NET 4.5 in VS2012 RTM and noticing something that I don't quite understand and that is unexpectedly green highlighted statements (instead of yellow).
Now I'm well aware of what this is supposed to mean, and the IDE is even showing me a little explanation tooltip.
This is the next statement to execute when this thread returns from
the current function
However there's absolutely nothing asynchronous or thread based about this code. In this simple example I'm sure you'll agree that string.ToUpper() won't be off in another thread. I can step through the code no issue.
There's nothing else going on and I am on the main thread as you can see here.
I am using async and await and MVVM-Light (the above method is the result of a RelayCommand) but I still get this behavior even when the code path is directly off an event handler such as PreviewKeyDown.
If I create a new app I cannot duplicate this - the coloring is yellow as expected - even when using await.
Anybody got any idea? It's starting to drive me crazy!!
It is green when the current instruction pointer is not exactly at the start of the statement. Some common causes:
Common in threaded code, setting a breakpoint in one thread and switching context to another. The other thread will have been interrupted by the debugger at an entirely random location. Often in code that you don't have source code or debugging info for, like String.ToUpper(), the debugger can only show the "closest" source code
Using Debugger + Break All to break into the debugger. Same idea as above, the instruction pointer will be at a random address
Getting an exception in code you don't have debugging info for. The editor shows the last entry in the Call Stack that it does have source code for. You need the call stack window to see where the actual exception was raised. Or the Exception Assistant, its reason for being
Debugging optimized code. The jitter optimizer scrambles the code pretty heavily, making it likely that the debugger can't show the current location accurately
Having out-dated debugging info or editing the code while debugging
Debugging code generated by the x64 jitter, happens when the project's Target Platform setting is AnyCPU. The x64 jitter has a number of chronic bugs that are not getting fixed, generating incorrect debugging info is one of them. Problems that were not addressed until it was completely rewritten, done by the RyuJIT project and first available in .NET version 4.6. Targeting x86 in your EXE project is the workaround.
I understand that this is old post yet I would like to answer the question with my experience.
I have encountered same issue recently in one of my WCF application. After debugging and closely looking service logs and I find out that my code was giving this error because service was hitting max allowed limit for code execution and once the service hit max allowed time limit it was trying to offload the current debugging session.
ERROR IN GREEN STATEMENT: this is the next statement to execute when thread return
So avoiding this issue you can try to look any potential code(Code/Service Timeout or any other code block) which is trying to offload your currently executing code context and try to fix it, furthermore original explanation given by #Hans is still very much relevant for trouble shooting this issue.
Actually, I am also facing this issue. This is because I missed some layout component in landscape mode, So check all the Id's and components and Run, you will not get this error.

Resources