11import pino from 'pino' ;
22import pretty from 'pino-pretty' ;
33import { context , trace } from '@opentelemetry/api' ;
4+ import { logs } from '@opentelemetry/api-logs' ;
45
56const stream = pretty ( {
67 colorize : true ,
@@ -10,6 +11,8 @@ const stream = pretty({
1011
1112const logger = pino ( stream ) ;
1213
14+ const otelLogger = logs . getLogger ( 'otel-pino-logger' ) ;
15+
1316export const getCurrentTraceIds = ( ) => {
1417 const span = trace . getSpan ( context . active ( ) ) ;
1518 return {
@@ -19,13 +22,16 @@ export const getCurrentTraceIds = () => {
1922} ;
2023
2124export const errorObjLog = ( error : unknown , message : string ) => {
22- const errorMessage = ( error as { message : string } ) . message
23- ? ( error as { message : string } ) . message
24- : 'Unknown error' ;
25-
26- const errorStack = ( error as { error : string } ) ? ( error as { error : string } ) . error : 'No stack trace available' ;
2725 const traceIds = getCurrentTraceIds ( ) ;
2826
27+ const errorMessage = ( error as { message ?: string } ) ?. message ?? 'Unknown error' ;
28+ const errorStack = ( error as { stack ?: string } ) ?. stack ?? 'No stack trace available' ;
29+
30+ otelLogger . emit ( {
31+ body : message ,
32+ ...traceIds ,
33+ } ) ;
34+
2935 logger . error (
3036 {
3137 ...traceIds ,
@@ -37,15 +43,23 @@ export const errorObjLog = (error: unknown, message: string) => {
3743 message ,
3844 ) ;
3945} ;
40-
4146export const errorLog = ( message : string ) => {
42- logger . error ( { ...getCurrentTraceIds ( ) } , message ) ;
43- } ;
47+ const traceIds = getCurrentTraceIds ( ) ;
4448
45- export const infoLog = ( message : string ) => {
46- logger . info ( { ...getCurrentTraceIds ( ) } , message ) ;
49+ otelLogger . emit ( { body : message , ... traceIds } ) ;
50+ logger . error ( { ...traceIds } , message ) ;
4751} ;
4852
4953export const warnLog = ( message : string ) => {
50- logger . warn ( { ...getCurrentTraceIds ( ) } , message ) ;
54+ const traceIds = getCurrentTraceIds ( ) ;
55+
56+ otelLogger . emit ( { body : message , ...traceIds } ) ;
57+ logger . warn ( { ...traceIds } , message ) ;
58+ } ;
59+
60+ export const infoLog = ( message : string ) => {
61+ const traceIds = getCurrentTraceIds ( ) ;
62+
63+ otelLogger . emit ( { body : message , ...traceIds } ) ;
64+ logger . info ( { ...traceIds } , message ) ;
5165} ;
0 commit comments