@zanemathew/si-logger
v10.0.3
Published
The Logger Library is a logging utility that provides functionality to log messages with different log levels and offers options to log to a file and send logs to a backend server.
Downloads
1
Readme
SiLogger
The Logger Library is a logging utility that provides functionality to log messages with different log levels and offers options to log to a file and send logs to a backend server.
Features
- Log messages with different log levels (ERROR, WARN, INFO).
- Log messages to a file.
- Optional logging to a backend server.
- Customizable log configuration.
- Environment variable integration for configuration.
Installation
You can install the Logger Library via npm:
npm i @zanemathew/si-logger
Usage
- Import the
SiLoggerModule
andLoggerConfig
into your Angular module and set your desired logging configurations:import { SiLoggerModule } from "@zanemathew/si-logger"; import { LoggerConfig } from "@zanemathew/si-logger/lib/interface/logger-config-interface"; // Pre-define the logger configuration, you can set dynamic configuration values if you wish. const loggerConfig: LoggerConfig = { apiURL: 'https://www.your-api.com', // the backend api URL logFileKey: `siLogMessages`, // the local storage file key logAsCSV: true, // set to true to set file log format as CSV, otherwise format will be in JSON enabledLogTypes: ['FILE','CONSOLE'], enabledLogLevels: ['INFO', 'DEBUG', 'ERRO'] } @NgModule({ imports: [ SiLoggerModule.forRoot(loggerConfig), ] }) export class AppModule { }
- Inject the SiLoggerService into your component or service:
import { SiLoggerService } from 'si-logger-library'; constructor(private logger: SiLoggerService) { }
- Start using the logger:
this.logger.info('This is an information message.'); this.logger.warn('This is a warning message.');
- The SiLoggerLibrary offers complete configurability to adapt to the specific logging requirements of your project or application. It also allows you to seamlessly incorporate a personalized UI marker (User Interface Marker) for an improved user experience, providing users with access to pre-built components and styles. This includes a visual representation or component that can be readily utilized within your application.
Example library implementation with UI Marker implemented.
app.module.ts
import {getLogLevels, getLogTypes, LogLevel, LogType, SiLoggerModule} from "@zanemathew/si-logger";
import {LoggerConfig} from "@zanemathew/si-logger/lib/interface/logger-config-interface";
// SiLogger Setup
const url = window.location.href;
const qryString = url.split('?')[1];
const queryParams = new URLSearchParams(qryString);
const enableLogger = queryParams.get('enableLogger');
const jsonFormat = queryParams.get('jsonFormat');
const requiredLogTypes = queryParams.getAll('logType') as LogType[];
const requiredLogLevels = queryParams.getAll('logLevel') as LogLevel[];
const validLogTypes = getLogTypes();
const validLogLevels = getLogLevels();
const allLogTypesValid = requiredLogTypes.every(type => validLogTypes.includes(type));
const allLogLevelsValid = requiredLogLevels.every(level => validLogLevels.includes(level));
// Define the logger configuration
const loggerConfig: LoggerConfig = {
apiURL: 'localhost', // the backend api URL
logFileKey: `siLogMessages-${jsonFormat === 'true' ? 'json':'csv'}`, // the local storage file key
logAsCSV: jsonFormat === 'true' ? false:true, // set to true to set file log format as CSV, otherwise format will be in JSON
enabledLogTypes: [],
enabledLogLevels: []
}
if (enableLogger==='true') {
// Set default log types and log levels if the logger is enabled
loggerConfig.enabledLogTypes = [LogType.CONSOLE] as LogType[];
loggerConfig.enabledLogLevels = [LogLevel.ERROR] as LogLevel[];
if (allLogTypesValid && requiredLogTypes.length > 0) {
// If all required log types are valid and there are required log types specified,
// update the enabled log types in the logger configuration
loggerConfig.enabledLogTypes = requiredLogTypes;
}
if (allLogLevelsValid && requiredLogLevels.length > 0) {
// If all required log levels are valid and there are required log levels specified,
// update the enabled log levels in the logger configuration
loggerConfig.enabledLogLevels = requiredLogLevels;
}
// Render the marker with the specified color, enabled log types, log file key, and log file type flag
renderMarker('lightgreen', loggerConfig.enabledLogTypes, loggerConfig.logFileKey, loggerConfig.logAsCSV);
}
// Function to render a marker element with the specified color, log types, log file key, and log type
export function renderMarker(color: string, logType: LogType[], logFileKey: string = '', logAsCSV: boolean): void {
const marker = document.createElement('div');
const content = document.createElement('div');
const toggleButton = document.createElement('button');
let isCollapsed = false;
// Set initial content visibility to block
content.style.display = 'block';
toggleButton.innerHTML = '⇿';
// Toggle button click event handler
toggleButton.addEventListener('click', () => {
// Toggle the visibility of the content based on the isCollapsed flag
isCollapsed = !isCollapsed;
content.style.display = isCollapsed ? 'none' : 'block';
});
// Set marker styles
marker.style.cssText = `
position: fixed;
bottom: 5px;
right: 5px;
background-color: ${color};
color: white;
padding: 5px;
z-index: 9999;
border-radius: 10px;
`;
// Set content with log types as text
content.textContent = logType.toString();
if (logType.includes(LogType.FILE)) {
// If log type includes FILE, handle file-related operations
const logData = localStorage.getItem(logFileKey) ?? '';
let type = logAsCSV ? 'csv' : 'json';
// Create a Blob with logData and set the appropriate type
const blob = new Blob([logData], {type: `application/${type}`});
// Create a download link for the log file
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.innerHTML = '↓';
link.download = `${logFileKey}.${type}`;
if (logData.length > 0) {
// Append the download link to the content if logData is not empty
content.appendChild(link);
}
}
// Append content and toggle button to the marker
marker.appendChild(content);
marker.appendChild(toggleButton);
// Append the marker to the document body
document.body.appendChild(marker);
}