Good application logging means choosing the right SLF4J level for each event, writing messages that carry enough context to diagnose a problem without opening the code, and reading other people’s logs by following one request from start to finish. As a Java intern you will be judged less on how much you log and more on whether a stranger could use your log lines at 2 a.m. This guide gives you the levels, the message rules, a scorecard and a practice worksheet.
What SLF4J is and why interns meet it first
SLF4J (Simple Logging Facade for Java) is an API, not a logging engine. Your code calls org.slf4j.Logger; a backend such as Logback or Log4j2 decides where the output goes, in what format and at what level. Spring Boot projects use SLF4J with Logback by default, so most internship codebases already have it wired up.
The practical consequence: you write log statements once, and operations teams change verbosity through configuration, not code. That only works if you pick levels honestly.
private static final Logger log = LoggerFactory.getLogger(OrderService.class);
log.info("Order placed orderId={} customerId={} total={}", orderId, customerId, total);
The {} placeholders avoid building the string when the level is disabled, and they keep messages consistent. Prefer them over string concatenation.
SLF4J log levels and when each one is correct
SLF4J defines five levels, from most to least verbose: TRACE, DEBUG, INFO, WARN, ERROR. Production usually runs at INFO or WARN, so anything below that is invisible when you need it unless someone raises the level.
| Level | Use it for | Illustrative example | Typical production visibility |
|---|---|---|---|
| TRACE | Very fine-grained flow, rarely enabled | Entering method with every parameter | Off |
| DEBUG | Diagnostic detail for developers | Cache miss for key, SQL parameters, branch taken | Usually off, enabled temporarily |
| INFO | Normal business and lifecycle events | Application started, order placed, job finished with counts | On |
| WARN | Something unexpected that the system handled | Retry 2 of 3 to payment gateway, deprecated API called | On |
| ERROR | An operation failed and needs attention | Order could not be saved; exception included | On, often triggers alerts |
Decision rules for the awkward cases
- User typed a wrong password: INFO or WARN at most, not ERROR. The system worked correctly. Hundreds of these as ERROR will bury real failures.
- Validation failure on a request: DEBUG or INFO, because the caller will get a 400 response anyway.
- Retry that later succeeds: WARN for each retry, INFO when it finally works.
- Exception you catch and recover from: WARN with the exception, not ERROR.
- Exception that fails the request: ERROR, logged once, at the boundary where it is handled.
Free 2-Week CareerSwami Internship
Online, 14 days, with a free offer letter and a free completion certificate once you finish the work. Check with your college that it fits your requirement before you enrol.
Writing log messages that someone can act on
A useful message answers four questions: what happened, to which entity, with what outcome, and why if it failed. Compare these two.
- Weak:
log.error("Error occurred"); - Better:
log.error("Payment capture failed orderId={} gateway={} status={}", orderId, gateway, status, ex);
Message rules to apply every time
- Use key=value pairs so logs can be searched and filtered.
- Pass the exception as the last argument so the stack trace prints. Do not use
ex.getMessage()alone, and do not callprintStackTrace(). - Log once. Either log and rethrow, or throw and let one handler log. Doing both produces duplicate stack traces.
- Never log secrets or personal data: passwords, OTPs, tokens, full card numbers, Aadhaar numbers. Log an ID instead.
- Avoid logging inside tight loops at INFO. Log a summary with counts afterwards.
- Write in plain past or present tense without shouting, emojis or vague words like “something went wrong”.
Add a correlation ID with MDC
SLF4J’s Mapped Diagnostic Context (MDC) lets you attach values such as a request ID to every line a thread writes. Put MDC.put("requestId", id) in a filter at the start of a request, remove it in a finally block, and include %X{requestId} in the Logback pattern. Without it, interleaved lines from concurrent users are very hard to untangle.
Reading production-style logs step by step
A typical line has a timestamp, level, thread, logger name and message. Illustrative format:
2026-11-13 10:42:07.311 WARN [http-nio-8080-exec-4] c.s.pay.GatewayClient - Retry attempt=2 maxAttempts=3 orderId=8841 reason=timeout
A repeatable reading routine
- Find the time window. Note when the user or alert says the problem began.
- Filter to WARN and ERROR inside that window.
- Find the first error, not the loudest. Later errors are often consequences.
- Follow one identifier (request ID, order ID) across lines and, if there are several services, across files.
- Read the stack trace from the “Caused by” at the bottom up to your own package names; that is usually where the root cause sits.
- Check what changed: a deployment, configuration edit or traffic spike just before the first error.
- Write down the hypothesis and the log line that supports it before touching code.
Basic monitoring signals beyond logs
Logs explain individual events; monitoring shows trends. In Spring Boot, the Actuator module can expose health and metrics endpoints, which tools can scrape. Even without a dashboard, learn to ask for four numbers: error rate, response time, request volume and resource use (memory, CPU, connection pool). A log line tells you one order failed; a metric tells you whether it is one order or all of them.
Logging quality scorecard for your own pull requests
Before you submit code, score each new log statement. Aim for at least 8 out of 10 on every line.
| Check | Points | Passes when |
|---|---|---|
| Correct level | 2 | Level matches the decision rules above |
| Identifies the entity | 2 | Contains an order, user or request ID |
| States the outcome | 1 | Says success, failure, retry or count |
| Explains the cause on failure | 1 | Includes reason or exception object |
| Uses placeholders | 1 | No string concatenation |
| Safe content | 2 | No secrets or personal data |
| Not duplicated or noisy | 1 | Not inside a hot loop; not logged twice |
Worked example: improving one failing flow
Illustrative scenario; no code was executed. A checkout method contains:
try {
paymentClient.capture(order);
} catch (Exception e) {
log.error("Error " + e.getMessage());
e.printStackTrace();
throw e;
}
Scoring it: wrong or vague message (0 on entity, 0 on outcome), concatenation (0), stack trace printed outside the logger, and log-and-rethrow means the upstream handler will log again. Total roughly 2 of 10.
Rewrite: let the exception propagate to a central handler, and log once there:
log.error("Checkout failed orderId={} customerId={} step=payment-capture", orderId, customerId, ex);
If you want local context without duplication, wrap and rethrow instead: throw new CheckoutException("Payment capture failed orderId=" + orderId, e);. The rewritten line scores 9 or 10 because it has a correct level, entities, outcome and cause, placeholders and no sensitive data.
Worksheet: interpret and rewrite these log lines
Work through the lines below on paper. For each, write what happened, whether the level is right, and a better version. Answer key hints follow the table.
| # | Log line (illustrative) | Your tasks |
|---|---|---|
| 1 | ERROR Login failed for user ravi password=Ravi@123 |
Spot the security problem; fix the level and content |
| 2 | INFO Something went wrong |
What is missing? Rewrite with context and level |
| 3 | DEBUG Processing item 1 ... INFO Processing item 2 ... (10,000 lines per run) |
Replace with a summary design |
| 4 | WARN Retry attempt=3 maxAttempts=3 orderId=8841 reason=timeout followed by ERROR Payment capture failed orderId=8841 |
Explain the sequence; what would you check first? |
| 5 | ERROR NullPointerException appearing twice with identical stack traces one millisecond apart |
Diagnose the cause of duplication |
| 6 | INFO HikariPool-1 - Connection is not available, request timed out after 30000ms repeated across many requests |
Interpret it; is INFO right? What metric would confirm the theory? |
| 7 | ERROR User not found id=552 (from a public lookup endpoint returning 404) |
Decide the correct level and justify it |
| 8 | INFO Order saved |
Add identifiers and outcome; decide if it is needed at all |
Answer key hints
- Never log passwords. Use
WARN Login failed userId=... reason=bad-credentialsor INFO. - No entity, step or cause. Something like
ERROR Invoice generation failed invoiceId=...with the exception. - Log at DEBUG per item if needed, and INFO once:
Import finished processed=10000 failed=3 durationMs=.... - Retries were exhausted; check the gateway’s status and network timeouts, then whether other orders show the same pattern.
- The exception was logged and rethrown, then logged again by a handler. Log once.
- Likely connection pool exhaustion, possibly from leaked connections or slow queries. This should be WARN or ERROR. Check active versus maximum pool connections.
- Usually INFO or DEBUG, since the system behaved correctly.
- Include
orderId,customerIdand total; keep at INFO only if it is a meaningful business event.
PTU students: logging practice, internship rules and what to verify
Puducherry Technological University describes itself on its official website as the first state university of Puducherry, formed on 5 September 2020 with UGC approval. Its B.Tech regulations, which a 2021 regulations PDF says apply to both constituent and affiliated colleges, set internship rules university-wide. That PDF is hosted on another college’s domain, and it dates from 2021, so check that it is still the current version.
According to that document, the B.Tech programme requires at least 6 weeks of internship in industry, a research lab or a higher-learning institution, in at most 3 spells during vacations. Each spell must last at least 2 weeks, and the internship carries 2 credits. Students need prior approval from the Head of Department and must submit a detailed report afterwards. Assessment appears only in the eighth-semester grade card, and industry project work in semester 8 does not count as an internship.
What this means for a Java learner: a 14-day internship matches the minimum length of one spell, so it could form part of the 6 weeks, but only if your department accepts it. The regulations text does not mention online internships, and nothing verified says that a certificate from a free programme will be accepted for credit. The free two-week online internship from CareerSwami gives a free offer letter and a free completion certificate after successful completion; it does not promise academic credit.
For your report, logging gives you concrete material: a before-and-after scorecard of log statements, the worksheet answers, and a description of how you traced a fault through a log file.
Verification steps for PTU students before you start
- Ask your Head of Department in writing whether an online two-week internship can count towards the 6-week requirement, and request approval by email before you begin.
- Ask which regulation version applies to your admission year, and get the current PDF from your department office or the university’s own site.
- Ask what the report must contain, its format and the submission deadline for the eighth-semester assessment.
- Check your own programme’s curriculum document for how internship credits are recorded.
- If you need placement-cell guidance, use the contact details on the Training and Placement Centre site, which a search excerpt listed, and confirm they are current.
Fourteen-day plan for learning logging during a two-week internship
| Days | Focus | Output |
|---|---|---|
| 1-2 | Set up a small Spring Boot project with SLF4J and Logback | Running app printing INFO logs |
| 3-4 | Apply the level decision rules to a simple REST service | Table of each log statement with its level and reason |
| 5-6 | Rewrite messages using key=value and placeholders | Scored before-and-after list |
| 7-8 | Add a request ID with MDC and tune the pattern | Logs traceable per request |
| 9-10 | Introduce deliberate faults (bad input, timeout) and read the logs | Short incident notes using the reading routine |
| 11-12 | Add Actuator health and metrics; set per-package levels in configuration | Screenshot or notes on endpoints and levels |
| 13 | Complete the worksheet from memory, then check it | Marked worksheet |
| 14 | Write the report and portfolio summary | Report draft for your department |
Frequently Asked Questions
Which SLF4J level should I use for caught exceptions?
Use WARN if the code recovers and the user is unaffected, and ERROR if the operation fails. Always pass the exception object as the final argument so the stack trace is kept.
Is it wrong to use System.out.println in a Java project?
In team projects, yes. It bypasses levels, formatting, rotation and configuration, so operations cannot filter or route it. Use a Logger instead.
Should I log request and response bodies?
Be careful. Bodies often contain personal or payment data. If you must, log at DEBUG, mask sensitive fields, and limit the size.
How do I change log levels without redeploying?
In Spring Boot you can set logging.level.com.yourapp=DEBUG in configuration. Whether runtime changes via Actuator are available depends on how the application is set up, so ask your mentor.
Why do my logs show the same error twice?
Most often the code logs the exception and rethrows it, and a global handler logs it again. Choose one place to log it.
Does a logging-focused internship count for PTU internship credit?
That is decided by your department, not by this guide. The 2021 regulations require Head of Department approval beforehand and a report afterwards; get written confirmation that a short online internship is acceptable.
What should I put in an internship report about logging?
Include your level decision table, a before-and-after of log statements with scores, one traced incident with the log lines that proved the cause, and what you would monitor in production.
Do I need a dashboard tool to practise monitoring?
No. Start with log files and Actuator endpoints on your own machine. Dashboards help later, but the habit of asking what the error rate and latency are matters first.
Related Java & Enterprise Software guides
- North East Adventist University Students: Teamwork Habits for Your First Java Project Team
- ICFAI University Jharkhand: Java Internship Projects Using Finance Domain Knowledge
- Sankalchand Patel University: A Checklist for Judging Whether Your Java Internship Offer Is Genuine
- All Java & Enterprise Software internship guides
Ready to put this into practice?
Join the free two-week CareerSwami online internship in Java & Enterprise Software. The internship, the offer letter and the completion certificate are free.














