This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

Logging Done Right – DEV Community


Writing efficient log messages is essential for the general observability of your software. On this information, we’re going to focus primarily on what to log, and methods to write efficient log messages.

The code examples are written in JavaScript for its easy syntax, however these tips are relevant to any programming language.

Let’s get began!



1. All log messages ought to begin with the category and performance identify

logger.information('[MyClass.myFunction] The log message');
Enter fullscreen mode

Exit fullscreen mode

Purpose: Shortly figuring out the place the log message comes from. It additionally provides uniqueness to the logs, guaranteeing that logs should not duplicated.



2. Add logs in all exception dealing with blocks

attempt {
    // code that may throw an error
} catch (error) {
    logger.error('[OrderService.placeOrder] Order placement failed: ' + error.message);
}
Enter fullscreen mode

Exit fullscreen mode

Purpose: Very essential for troubleshooting.



3. Embrace context if helpful

logger.warn('[PaymentGateway.processPayment] Cost failed for UserID: 123, OrderID: 456, Error: Inadequate funds');
Enter fullscreen mode

Exit fullscreen mode

Purpose: Context helps you perceive the situations underneath which the log was generated, aiding in replicating and fixing points.



4. Add logs for auditing

logger.information('[OrderService.placeOrder] Order ID: 12345 positioned efficiently');
Enter fullscreen mode

Exit fullscreen mode

Purpose: Audit logs have many advantages, equivalent to reconstructing the timeline of a system outage or a safety breach, and in addition with the ability to detect them whereas taking place.



5. Do not embrace massive log messages if not mandatory

Unhealthy:

logger.information('[SomeOrdersJob.processOrders] Completed processing orders chunk, index: ' + chunkIndex + 'orders: ' + JSON.stringify(orders));
Enter fullscreen mode

Exit fullscreen mode

Good:

logger.information('[SomeOrdersJob.processOrders] Completed processing orders chunk, index: ' + chunkIndex + 'orders size: ' + orders.size);
Enter fullscreen mode

Exit fullscreen mode

Purpose: Giant log messages scale back readability, eat more room, and may introduce efficiency implications.



6. Do not log delicate information

Unhealthy, too dangerous:

logger.warn('[AuthService.login] Person login try failed, login information: ' + JSON.stringify(loginData));
Enter fullscreen mode

Exit fullscreen mode

logger.warn('[PaymentGateway.registerPaymentCard] Card registration failed, card information: ' + JSON.stringify(cardData));
Enter fullscreen mode

Exit fullscreen mode

Good:

logger.warn('[AuthService.login] Person login try failed, username: ' + loginData.username);
Enter fullscreen mode

Exit fullscreen mode

Purpose: Logging delicate information can create safety dangers and violate privateness laws equivalent to GDPR. At all times sanitize information earlier than logging. It’s extremely prone to overlook sanitizing your information when logging HTTP requests and responses, for instance.



7. Use the right log degree

logger.debug('[OrderService.placeOrder] Inside placeOrder operate');
logger.information('[OrderService.placeOrder] Order ID: 12345 positioned efficiently');
logger.warn('[AuthService.login] Person login try failed, username: ' + loginData.username);
logger.error('[OrderService.placeOrder] Order placement failed: ' + error.message);
logger.deadly('[Database.connect] Unable to hook up with the database: ' + error.message);
Enter fullscreen mode

Exit fullscreen mode

Purpose: Utilizing log ranges has many advantages, equivalent to filtering logs primarily based on their degree, taking particular actions equivalent to sending an alert for high-severity logs.



8. Timestamp your logs

logger.information('[2024-06-08T12:00:00Z] [OrderService.placeOrder] Order ID: 12345 positioned efficiently');
Enter fullscreen mode

Exit fullscreen mode

Purpose: Timestamps present a chronological order to logs, making it simpler to trace and perceive the sequence of actions. Additionally they mean you can troubleshoot points that occurred at particular occasions.



9. Keep away from logging in loops or recursive features if not mandatory

Unhealthy:

for (let i = 0; i < objects.size; i++) {
    logger.information('[InvoiceCalculator.calculate] Calculating merchandise: ' + i);
    // calculation logic
}
Enter fullscreen mode

Exit fullscreen mode

Good:

logger.information('[InvoiceCalculator.calculate] Calculation began');
for (let i = 0; i < objects.size; i++) {
    // calculation logic
}
logger.information('[InvoiceCalculator.calculate] Calculation completed');
Enter fullscreen mode

Exit fullscreen mode

Purpose: Extreme log entries make it more durable to search out related data, eat more room, and may result in efficiency points.



10. Log the beginning and finish of long-running operations

logger.information('[DataImportService.importData] Information import began');

// long-running operation

logger.information('[DataImportService.importData] Information import accomplished');
Enter fullscreen mode

Exit fullscreen mode

Purpose: It helps you monitor the progress and period of those operations.



11. Guarantee log messages are concise and clear

Unhealthy:

logger.information('[OrderService.placeOrder] The order placement operate has efficiently accomplished processing the order with ID 12345');
Enter fullscreen mode

Exit fullscreen mode

Good:

logger.information('[OrderService.placeOrder] Order ID: 12345 positioned efficiently');
Enter fullscreen mode

Exit fullscreen mode

Purpose: Concise and clear log messages are simpler to learn and perceive.



Conclusion

I hope you discovered this information useful. Please be happy to counsel different practices that you just assume are vital, and I might be pleased to incorporate them.



References and Additional Studying

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?