← Back to Advanced Java Course | Chapter 11: Advanced & Security | Lesson 14 of 19

Java में Logging (Log4j/SLF4J)

Logging आपके program से यह notes लिखवाना है कि वह क्या कर रहा है, जैसे एक diary। ये notes बाद में समस्याएं ढूंढने में मदद करते हैं।
Syntax
java
private static final Logger logger = LoggerFactory.getLogger(ClassName.class);

logger.info("message {}", value);
logger.error("message", exception);

Why Logging?

Logging runtime के दौरान program events को होते ही record करने की practice है। यह अपने code में जगह-जगह System.out.println() calls बिखेरने का एक कहीं ज़्यादा मज़बूत विकल्प है, क्योंकि यह आपको messages को severity से categorize करने, उन्हें अलग-अलग destinations पर route करने, और source code बदले बिना categories को on या off करने देता है।

उदाहरण: Why Logging?

java
import java.util.logging.Logger;
public class Main {
	static final Logger logger = Logger.getLogger(Main.class.getName());
	public static void main(String[] args) {
		logger.info("Categorized, routable log message"); // more robust than System.out.println
	}
}

Java Native Logger

built-in java.util.logging package (अक्सर JUL कहा जाता है) बिना किसी external dependency के built-in logging features प्रदान करता है, जो इसे छोटे applications के लिए एक उचित शुरुआती बिंदु बनाता है, भले ही बड़े projects अक्सर ज़्यादा feature-rich third-party framework पसंद करते हों।

उदाहरण: Java Native Logger

java
import java.util.logging.Logger;
public class Main {
	public static void main(String[] args) {
		Logger logger = Logger.getLogger("com.example.app"); // java.util.logging, zero external dependencies
		logger.info("Application started");
	}
}

Log Levels

Log levels messages को उनके महत्व या गंभीरता के अनुसार categorize करते हैं -- routine informational events के लिए INFO, अभी तक failures न बनी संभावित समस्याओं के लिए WARNING, और critical errors के लिए SEVERE -- आपको किसी दिए गए समय पर जिस severity level की परवाह है सिर्फ उसी के लिए output filter करने देते हुए।

उदाहरण: Log Levels

java
// Import java.util.logging.* so it can be used by its short name
import java.util.logging.*;
// Define the class Main
public class Main {
	static final Logger logger = Logger.getLogger(Main.class.getName());
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		logger.info("Routine event");
		logger.warning("Potential issue");
		logger.severe("Critical error");
	}
}

File Handlers

FileHandlers log output को सिर्फ console के बजाय server की disk पर असली files में redirect करते हैं, यह सुनिश्चित करते हुए कि console session या terminal बंद होने के बाद भी आपके पास क्या हुआ उसका एक persistent, searchable history हो।

उदाहरण: File Handlers

java
import java.util.logging.*;
public class Main {
	public static void main(String[] args) throws Exception {
		Logger logger = Logger.getLogger(Main.class.getName());
		FileHandler fileHandler = new FileHandler("app.log"); // persists to disk, not just console
		logger.addHandler(fileHandler);
		logger.info("Written to app.log");
		fileHandler.close();
		new java.io.File("app.log").delete();
	}
}

SLF4J and Log4j Wrappers

Enterprise applications आमतौर पर SLF4J को एक logging facade के रूप में उपयोग करती हैं -- एक standardized API जो आपके code को किसी specific logging implementation से decouple करती है, आपको बाद में Log4j, Logback, या किसी दूसरे backend framework को प्लग करने देते हुए बिना अपने codebase में हर logging call फिर से लिखे।

उदाहरण: SLF4J and Log4j Wrappers

java
public class Main {
	interface Logger { void info(String msg); } // a facade like SLF4J -- decoupled from any specific backend
	static class ConsoleLogger implements Logger {
		public void info(String msg) { System.out.println("[INFO] " + msg); }
	}
	public static void main(String[] args) {
		Logger logger = new ConsoleLogger(); // could be swapped for Log4j/Logback later
		logger.info("Facade decouples code from the logging backend");
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. + concatenation से log messages बनाना, जबकि logger.info("User {}", name) जैसे SLF4J placeholders level off होने पर यह काम टाल देते हैं।
  2. passwords या दूसरे sensitive data को log करना, जो फिर log files में बैठे रहते हैं।
  3. किसी catch block में सिर्फ e.getMessage() log करना, जिससे stack trace खो जाता है; exception को खुद logger को पास करें।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.