Created
May 13, 2024 14:14
-
-
Save gunzip/1d6b72868b880101141e47d9aee23663 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import appinsights from 'applicationinsights'; | |
import winston from 'winston'; | |
import { transports, format, Logger } from 'winston'; | |
// Configura Application Insights | |
appinsights.setup(process.env.APPINSIGHTS_INSTRUMENTATIONKEY) | |
.setAutoCollectConsole(false) | |
.start(); | |
const aiClient = appinsights.defaultClient; | |
// Crea un trasporto personalizzato per Application Insights | |
const appInsightsTransport = new transports.Stream({ | |
stream: { | |
write: (message: string) => { | |
const info = JSON.parse(message); | |
aiClient.trackTrace({ | |
message: info.message, | |
severity: convertLevelToAISeverity(info.level) | |
}); | |
} | |
}, | |
level: 'info' // Imposta il livello minimo del log a 'info' | |
}); | |
// Funzione per convertire il livello di log di Winston in livelli di severità di Application Insights | |
function convertLevelToAISeverity(level: string): number { | |
switch (level) { | |
case 'error': return appinsights.Contracts.SeverityLevel.Error; | |
case 'warn': return appinsights.Contracts.SeverityLevel.Warning; | |
case 'info': return appinsights.Contracts.SeverityLevel.Information; | |
default: return appinsights.Contracts.SeverityLevel.Verbose; | |
} | |
} | |
// Configura il logger di Winston | |
const logger: Logger = winston.createLogger({ | |
format: format.combine( | |
format.json(), // Usa il formato JSON per i messaggi | |
format.timestamp() | |
), | |
transports: [ | |
appInsightsTransport, | |
new transports.Console() // Puoi mantenere questo se vuoi che i log siano mostrati anche in console | |
] | |
}); | |
// Esempio di utilizzo del logger | |
logger.info('This is an informational message'); | |
logger.warn('This is a warning message'); | |
logger.error('This is an error message'); | |
export default logger; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment