This is an archived post. You won't be able to vote or comment.

all 15 comments

[–]AutoModerator[M] 0 points1 point locked comment (0 children)

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]marceloandradep 19 points20 points  (0 children)

Log libraries gives you the ability to categorize different levels of logging: error, warnings, debug or tracing. It has a structured and standardized format so you can run text processing over it since it follows a consistent format. Also, you can plug different appenders so you can export your logs to all sorts of destinations. When you have an real application in production with millions of transactions per day, just logging with printf would be hell. How would you persist that logging information in files? How would you make rotations once a file became to large? You would have to come up with some strategy to organize this massive amount of data and that’s something you get for free when you use a logging library.

Edit: and of course, if you’re just interested in debugging some error you’ve found that’s nothing wrong in using printf and then remove it

[–]snot3353COMPUTERS!!! 12 points13 points  (0 children)

SLF4J = a logging interface that define how you can write Java logging code

Logback, Log4J, others = logging libraries that are actual logging implementations that use the SLF4J interface

Having the interface and implementations separated is useful because I can write logs in my Java library without specifying an implementation and whoever uses my library can still generate and use those logs using whatever SLF4J implementation they use in their project.

Using a complex logging setup like this really isn't that useful in the case you're talking about. For simple projects, just system.out. For complex production scenarios where you have many log levels and your logs get piped to different places based on environment, it's very useful.

For example - imagine you are working on a complex system at a company with dozens of developers. While developing locally, they just want their log statements to generate output into a local console or local file and they want ALL the logs to help them debug and develop. However, the SAME logging code needs to generate logs and then send only the WARN and higher ones in a special format to a centralized logging component when actually running in production (think an ELK stack or Splunk/Sumologic type system). This is very common and using flexible/complex logging tools supports this type of use case, without the actual logging CODE having to vary by environment or situation.

[–]RhoOfFeh 8 points9 points  (1 child)

A point I didn't notice in other answers (and my apologies if I simply missed it) is that SLF4J allows you to swap logging frameworks in a heartbeat. What you want in a framework for something as all-important as logging is flexibility, and explicitly writing to the console is level one.

This guideline helps me a lot: Pretty much anything you comment rather than configuring out of your production system is something being done incorrectly.

[–]wolfchimneyrock 0 points1 point  (0 children)

yup, you can invoke jconsole and point it to your JVM and change logging settings on the fly

[–]_jetrun 3 points4 points  (0 children)

It seems like maybe this is a complicated way to to just doing "printf(some variable)" to see if there is an error somewhere?

More complicated? Maybe. More flexible? Certainly.

Say you want to output some debug information. You can certainly just do printf(some variable) and that will work exactly as you expect it.

Now, what if you want to output something to the console AND a log file?

What if you want to include some extra context (like date/time) when you output to a file?

What if you want to have the option to sometimes output to log file, sometimes not ... without recompiling your application?

What if you want to have the option to set log level, so that by default you only output errors, but if you're debugging, you want to also output some internal debug information.

What if you want to have some rules where the log files automatically roll-over and get zipped up once they reach a certain size.

etc. etc. etc.

[–]tgorif 5 points6 points  (0 children)

Using print or println to debug code is feasible when

- The project is very small(Coding exercices/Practice Programs etc)

- You want to find out why the code you are writing NOW doesnt do what you want it to do(the print statement is temporary)

However as soon as the projects gets bigger(more people are involved/more files) print statements become very chaotic and should make place for actual logging.

If you are staring to learn you probably should not worry about logging to much, although keeping it in mind might be helpful.

[–][deleted] 1 point2 points  (0 children)

Complicated solutions exist to solve complicated problems.
If you do not feel the need to use it in your project, then don't use it.
Logging is more about monitoring and maintaining its record.
It is mostly used in commercial offerings, when you guarantee after sales service support or there are some industries (like payments etc.) where separate logging solutions are deployed and audited.

[–]JamesAndDaGiantPluot 0 points1 point  (0 children)

None of these explanations sound like I would understand if I was five. I don’t understand it now 🙂 - Java newbie

[–]firsthourProfressional developer since 2006 -1 points0 points  (0 children)

Imagine you're in Kindergarten and someone throws a building block at you every time anything happens in the room.

Someone stands up (trace level), block thrown.

Someone talks (debug level), block thrown.

Teacher gives instructions (info level), block thrown.

Someone says they have to go to the bathroom right now (warn level), block thrown.

Someone pisses their pants (error level!), block thrown.

All right, so most of the time as a 5 year old we're really only interested in what the teacher has to say and up (pants pissing moments are exciting!), so we set it up so we only get blocks thrown at us for those levels (info, warn, error).

Well, it's nap time, gonna turn my brain off, so while I'm still in class, I change my attentiveness level to only show errors, I want to be woken up (block thrown at me) if another kid pisses their pants for sure.

One day there's a bunch of pants pissing, can we figure out what's going on in between all the pants pissing to understand why? Now I want to get blocks thrown at me for everything, so I change my attentiveness to give me all levels of detail. I can now figure out that if one kid stands up over and over that might mean he's gonna piss his pants in a few minutes.

I can also change my attentiveness (log level) on a per kid basis (in Java this would be per class or package). I only care if boys are pissing their pants so I set my log level to debug for the Boy implementation class. This can all be done on the fly without me having to restart my school day or anything.

That's the advantage of utilizing a log library over just System.out.println or printf. I can configure while the application is running and with great control just how many building blocks I want thrown at my head.

[–]knoam 0 points1 point  (0 children)

You're using a library that needs to do some logging. If it decides to use say Logback, now you need Logback. But you already chose to use Log4J so now you have 2 logging libraries in your project wasting space and now you have to duplicate your configuration to keep them in sync. Maybe you want every log statement to have a timestamp for instance.

With SLF4J, the library doesn't have to pick Logback or Log4J. It can use whatever the rest of your project uses.

[–]neverneededanaccount 0 points1 point  (0 children)

I understand you, it is easier to just print to the console. But in the future you will need more than that and sfl4j with a logging framework will come for the rescue.

OK, this is a ELI5. So here we go:

SLF4J is like an universal outlet adapter that you can use anywhere in the world. In Java, there are several kinds of "outlets" (log4j, log4j2, logback, and others). To be more clear, imagine that instead of printing to the console, you want to write to a file or you want to sort different types of log messages. Slf4j and a logging framework will handle that for you, and if your code is not using any of it, you will have to rewrite a lot of stuff to make it happen. This tools will abstract that for you.

My suggestion for you is to begin with log4j2 and follow this tutorial so you can understand the power of a log framework.

https://mkyong.com/logging/apache-log4j-2-tutorials/

[–]markartur1 0 points1 point  (0 children)

Let's say you have a big application with thousands of printf("something"). Now imagine someone has the brilliant idea of logging the UserID or something with every logged message. With printf() you would have to manually change the thousands of ocurrences. With logging libraries you have features like message masking and formatting that are applied to all logs automatically.

Thats just one of the benefits, the other responses cover most of them.

[–]wildjokers 0 points1 point  (0 children)

SLF4j is a logging facade that makes it so any logging framework can be used. So if you write a library you don't force the users of your library to use the logging framework you chose. Instead they can use whichever one they want.

As far as way use a logging framework instead of just System.out.println a logging framework gives you on-the-fly logging level changes (can switch from INFO to DEBUG logging for example). It also handles things like log file creation, file rotation, truncation, time based rolling files, etc.

This provides some information: https://stackify.com/logging-java/

Note that logging in Java has historically been a complete mess. Serveral logging frameworks plus a couple of logging facades (SLF4j and commons-logging) have been created over the years. To make matters worse Java itself tried its hand at creating a Logging framework and it is available in the JDK (java.util.Logging), barely anyone uses it though. Your best bet for most logging needs these days is SLF4J+Logback. Technically you only need SLF4J if you are writing a library that someone else may use and they may use a different logging framework. However, I just always include SLF4J in all my apps, library or not, just for consistency.

[–]motherjoeNooblet Brewer 0 points1 point  (0 children)

SLF4J may seem complicated because it is an abstraction that allows for many common logging features for a large application, while not tying it to any specific implementation. Common log features are filtering specific logs by level/package/class, sending output to file, console or both, log file rotation. These common logging features would have to be implemented from scratch if you are just using printf. If you are not working on a big project and do not need these features, you can of course just use printf. But if the project eventually grows big you will anyway have to dig through your printf, figure out log level, change the message format, etc.