Simple Angular Log Service
Nhan Nguyen
Posted on June 29, 2024
Logging is an essential part of any software development process.
It helps developers debug applications, understand workflows, and track down issues.
In this article, I would like to introduce a simple logging service that can be easily integrated into our Angular application.
It uses an enumerated log level to control what messages are logged based on the current environment configuration.
Log Levels Enum
export const LOG_LEVEL = {
info: 1,
error: 2,
warn: 3,
debug: 4,
all: 5,
} as const;
Environment Configuration
// environment.ts (Development)
export const environment = {
production: false,
logLevel: LOG_LEVEL.debug
};
// environment.prod.ts (Production)
export const environment = {
production: true,
logLevel: LOG_LEVEL.info
};
Log Service
export class LogService {
log(message?: any, ...optionalParams: any[]) {
if (environment.logLevel >= LOG_LEVEL.debug) {
console.log(...[message, ...optionalParams]);
}
}
table(message?: any, ...optionalParams: any[]) {
if (environment.logLevel >= LOG_LEVEL.debug) {
console.table(...[message, ...optionalParams]);
}
}
trace(message?: any, ...optionalParams: any[]) {
if (environment.logLevel >= LOG_LEVEL.debug) {
console.trace(...[message, ...optionalParams]);
}
}
error(message?: any, ...optionalParams: any[]) {
if (environment.logLevel >= LOG_LEVEL.error) {
console.error(...[message, ...optionalParams]);
}
}
debug(message?: any, ...optionalParams: any[]) {
if (environment.logLevel >= LOG_LEVEL.debug) {
console.debug(...[message, ...optionalParams]);
}
}
info(message?: any, ...optionalParams: any[]) {
if (environment.logLevel >= LOG_LEVEL.info) {
console.info(...[message, ...optionalParams]);
}
}
warn(message?: any, ...optionalParams: any[]) {
if (environment.logLevel >= LOG_LEVEL.warn) {
console.warn(...[message, ...optionalParams]);
}
}
}
And how to Use the Log Service
To start using the LogService, just inject it into our components or services like this:
export class AppComponent implements OnInit {
private logService = inject(LogService);
ngOnInit() {
this.logService.info('Application initialized');
this.logService.debug('Debugging information');
}
}
Conclusion
By using this LogService, we can gain better control over your logging output, ensuring that we have detailed logs in development while keeping our production environment clean and efficient.
I hope you found it helpful. Thanks for reading. π
Let's get connected! You can find me on:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
- Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyendevjs
Posted on June 29, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.