In this lesson, you will learn how to adjust your application’s log verbosity dynamically based on the environment your code is running in.
When you are developing locally, you often want "noisy" logs—detailed messages that track every variable change or function call. However, in a production environment, printing every minor detail can clutter your logs, increase costs, and potentially expose sensitive information.
The Strategy: Level-Based Logging
Instead of hardcoding your console.log statements, we use the Twelve-Factor principles you learned earlier to control verbosity via environment variables. By defining a LOG_LEVEL variable, we can decide which logs actually reach the console.
Consider this simple pattern:
// config.js
export const LOG_LEVEL = process.env.LOG_LEVEL || 'info';
// logger.js
import { LOG_LEVEL } from './config.js';
const levels = { debug: 0, info: 1, error: 2 };
export const log = (message, level = 'info') => {
// Only log if the current level is equal to or higher than the configured one
if (levels[level] >= levels[LOG_LEVEL]) {
console.log(`[${level.toUpperCase()}]: ${message}`);
}
};
Implementing the Environment Switch
In your local environment, you might start your app with LOG_LEVEL=debug node index.js to see everything. In your CI/CD pipeline or production deployment, you would set LOG_LEVEL=error, ensuring that only critical failures are recorded.
This approach decouples your code logic from your runtime environment. By using a configuration hierarchy, you ensure that you don't have to change your application code just to change how much information it reports. Whether you are debugging a tricky local edge case or monitoring a stable production service, you maintain full control by simply toggling the environment variable at execution time.
Key Takeaway: Use environment variables to toggle log verbosity, ensuring your application remains descriptive during development but concise and performant in production.