-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathlogger.ts
More file actions
268 lines (237 loc) · 7.54 KB
/
Copy pathlogger.ts
File metadata and controls
268 lines (237 loc) · 7.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import { appendFileSync, existsSync, mkdirSync, unlinkSync } from 'fs'
import path, { dirname } from 'path'
import { format as stringFormat } from 'util'
import { AnalyticsEvent } from '@codebuff/common/constants/analytics-events'
import { env, IS_DEV, IS_TEST, IS_CI } from '@codebuff/common/env'
import { createAnalyticsDispatcher } from '@codebuff/common/util/analytics-dispatcher'
import { getAnalyticsEventId } from '@codebuff/common/util/analytics-log'
import {
isFullTelemetryEnabled,
summarizeAnalyticsValue,
} from '@codebuff/common/util/analytics-sampling'
import { pino } from 'pino'
import {
flushAnalytics,
logError,
setAnalyticsErrorLogger,
trackEvent,
} from './analytics'
import { getCurrentChatDir, getProjectRoot } from '../project-files'
export interface LoggerContext {
userId?: string
userEmail?: string
clientSessionId?: string
fingerprintId?: string
clientRequestId?: string
[key: string]: any // Allow for future extensions
}
export const loggerContext: LoggerContext = {}
let logPath: string | undefined = undefined
let pinoLogger: any = undefined
const loggingLevels = ['info', 'debug', 'warn', 'error', 'fatal'] as const
type LogLevel = (typeof loggingLevels)[number]
const analyticsDispatcher = createAnalyticsDispatcher({
envName: env.NEXT_PUBLIC_CB_ENVIRONMENT,
bufferWhenNoUser: true,
})
/**
* Safely stringify an object, handling circular references.
* Replaces circular references with '[Circular]' placeholder.
*/
function safeStringify(obj: unknown): string {
const seen = new WeakSet()
return JSON.stringify(obj, (_key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return '[Circular]'
}
seen.add(value)
}
return value
})
}
function isEmptyObject(value: any): boolean {
return (
value != null &&
typeof value === 'object' &&
!Array.isArray(value) &&
Object.keys(value).length === 0
)
}
function setLogPath(p: string): void {
if (p === logPath) return // nothing to do
logPath = p
mkdirSync(dirname(p), { recursive: true })
// ──────────────────────────────────────────────────────────────
// pino.destination(..) → SonicBoom stream, no worker thread
// ──────────────────────────────────────────────────────────────
const fileStream = pino.destination({
dest: p, // absolute or relative file path
mkdir: true, // create parent dirs if they don’t exist
sync: true, // set true if you *must* block on every write
})
pinoLogger = pino(
{
level: 'debug',
formatters: {
level: (label) => ({ level: label.toUpperCase() }),
},
timestamp: () => `,"timestamp":"${new Date().toISOString()}"`,
},
fileStream, // <-- no worker thread involved
)
}
export function clearLogFile(): void {
const projectRoot = getProjectRoot()
const defaultLog = path.join(projectRoot, 'debug', 'cli.jsonl')
const targets = new Set<string>()
if (logPath) {
targets.add(logPath)
}
targets.add(defaultLog)
for (const target of targets) {
try {
if (existsSync(target)) {
unlinkSync(target)
}
} catch {
// Ignore errors when clearing logs
}
}
logPath = undefined
pinoLogger = undefined
}
function sendAnalyticsAndLog(
level: LogLevel,
data: any,
msg?: string,
...args: any[]
): void {
if (!IS_CI && !IS_TEST) {
let projectRoot: string | undefined
try {
projectRoot = getProjectRoot()
} catch {
projectRoot = undefined
}
if (projectRoot) {
const logTarget =
IS_DEV
? path.join(projectRoot, 'debug', 'cli.jsonl')
: path.join(getCurrentChatDir(), 'log.jsonl')
setLogPath(logTarget)
}
}
const isStringOnly = typeof data === 'string' && msg === undefined
const normalizedData = isStringOnly ? undefined : data
const normalizedMsg = isStringOnly ? (data as string) : msg
const includeData = normalizedData != null && !isEmptyObject(normalizedData)
const toTrack = {
...(includeData ? { data: normalizedData } : {}),
level,
loggerContext,
msg: stringFormat(normalizedMsg, ...args),
}
logAsErrorIfNeeded(toTrack)
if (!IS_DEV && includeData && typeof normalizedData === 'object') {
const analyticsPayloads = analyticsDispatcher.process({
data: normalizedData,
level,
msg: stringFormat(normalizedMsg ?? '', ...args),
fallbackUserId: loggerContext.userId,
})
analyticsPayloads.forEach((payload) => {
trackEvent(payload.event, payload.properties)
})
}
// Send all log events to PostHog in production for better observability
// Skip if the log already has an eventId (to avoid duplicate tracking)
const hasEventId = includeData && getAnalyticsEventId(normalizedData) !== null
if (!IS_DEV && !IS_TEST && !IS_CI && !hasEventId) {
const fullTelemetry = isFullTelemetryEnabled({
distinctId: loggerContext.userId,
properties: loggerContext,
})
const includeRawData =
fullTelemetry || level === 'error' || level === 'fatal'
const dataProperties =
includeData && includeRawData
? { data: normalizedData }
: includeData
? { dataSummary: summarizeAnalyticsValue(normalizedData) }
: {}
trackEvent(AnalyticsEvent.CLI_LOG, {
level,
msg: stringFormat(normalizedMsg ?? '', ...args),
...dataProperties,
...loggerContext,
})
}
// In dev mode, use appendFileSync for real-time logging (Bun has issues with pino sync)
// In prod mode, use pino for better performance
if (IS_DEV && logPath) {
const logEntry = safeStringify({
level: level.toUpperCase(),
timestamp: new Date().toISOString(),
...loggerContext,
...(includeData ? { data: normalizedData } : {}),
msg: stringFormat(normalizedMsg ?? '', ...args),
})
try {
appendFileSync(logPath, logEntry + '\n')
} catch {
// Ignore write errors
}
} else if (pinoLogger !== undefined) {
const base = { ...loggerContext }
const obj = includeData ? { ...base, data: normalizedData } : base
pinoLogger[level](obj, normalizedMsg as any, ...args)
}
}
function logAsErrorIfNeeded(toTrack: {
data?: any
level: LogLevel
loggerContext: LoggerContext
msg: string
}) {
if (toTrack.level === 'error' || toTrack.level === 'fatal') {
logError(
new Error(toTrack.msg),
toTrack.loggerContext.userId ?? 'unknown',
{ ...(toTrack.data ?? {}), context: toTrack.loggerContext },
)
flushAnalytics()
}
}
/**
* Wrapper around Pino logger.
*
* To also send to Posthog, set data.eventId to type AnalyticsEvent
*
* e.g. logger.info({eventId: AnalyticsEvent.SOME_EVENT, field: value}, 'some message')
*/
export const logger: Record<LogLevel, pino.LogFn> = Object.fromEntries(
loggingLevels.map((level) => {
return [
level,
(data: any, msg?: string, ...args: any[]) =>
sendAnalyticsAndLog(level, data, msg, ...args),
]
}),
) as Record<LogLevel, pino.LogFn>
setAnalyticsErrorLogger((error, context) => {
const err =
error instanceof Error ? error : new Error(typeof error === 'string' ? error : 'Unknown analytics error')
logger.warn(
{
analyticsError: true,
error: {
name: err.name,
message: err.message,
stack: err.stack,
},
context,
},
'[analytics] error',
)
})