Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve developer logging of requests #1394

Merged
merged 7 commits into from
Oct 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backend/src/routes/middleware/defaultAuthentication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export function checkAuthentication(req, res, next) {
if (!req.user) {
throw Unauthorized('No valid authentication provided.')
}
req.log.debug(
req.log.trace(
{
user: req.user,
},
Expand Down
2 changes: 1 addition & 1 deletion backend/src/routes/middleware/expressLogger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const morganLog = promisify(
requestId: req.reqId,
...(tokens.res(req, res, 'content-length') && { 'content-length': tokens.res(req, res, 'content-length') }),
}
req.log.trace(info, `Request completed.`)
req.log.debug(info, 'Request completed')

return ''
},
Expand Down
38 changes: 32 additions & 6 deletions backend/src/services/log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ interface BunyanLog {
src: { file: string; line: number }
msg: string
}

interface RequestCompletedLog extends BunyanLog {
method: string
url: string
status: number
'response-time': number
ARADDCC012 marked this conversation as resolved.
Show resolved Hide resolved
}

export function isBunyanLogGuard(data: unknown): data is BunyanLog {
if (typeof data !== 'object' || data === null) {
return false
Expand Down Expand Up @@ -63,7 +71,7 @@ export class Writer extends WritableStream {
}

getSrc(src: { file: string; line: any }) {
const line = src.file.replace(this.basepath, '')
const line = src.file.replace(this.basepath, '').replace('file://', '')

if (line.startsWith('routes/middleware/expressLogger.ts')) {
return 'express'
Expand All @@ -76,6 +84,19 @@ export class Writer extends WritableStream {
return typeof value === 'object' ? util.inspect(value) : String(value)
}

static isRequestCompleted(data: unknown): data is RequestCompletedLog {
if (typeof data !== 'object' || data === null) {
return false
}

if (!('msg' in data) || typeof data.msg !== 'string') {
return false
}

const keys = Object.keys(data)
return ['requestId', 'url', 'method'].every((k) => keys.includes(k)) && data.msg === 'Request completed'
}

static getAttributes(data: any) {
let attributes = omit(data, [
'name',
Expand All @@ -92,9 +113,9 @@ export class Writer extends WritableStream {
])
let keys = Object.keys(attributes)

if (['id', 'url', 'method', 'response-time', 'status'].every((k) => keys.includes(k))) {
if (Writer.isRequestCompleted(data)) {
// this is probably a req object.
attributes = omit(attributes, ['id', 'url', 'method', 'response-time', 'status'])
attributes = omit(attributes, ['requestId', 'agent'])
keys = Object.keys(attributes)
}

Expand All @@ -121,9 +142,14 @@ export class Writer extends WritableStream {
const level = Writer.getLevel(data.level)
const src = data.src ? this.getSrc(data.src) : undefined
const attributes = Writer.getAttributes(data)
const formattedAttributes = attributes.length ? ` (${attributes})` : ''
const formattedAttributes = attributes.length ? `${data.msg ? ' ' : ''}(${attributes})` : ''

const message = `${level} - (${src}): ${data.msg}${formattedAttributes}`
let message
if (Writer.isRequestCompleted(data)) {
message = `${level} - ${data.status} ${data.method} ${data.url} ${data['response-time']}ms`
} else {
message = `${level} - (${src}): ${data.msg}${formattedAttributes}`
}

const pipe = data.level >= 40 ? 'stderr' : 'stdout'
process[pipe].write(`${message}\n`)
Expand All @@ -145,7 +171,7 @@ if (process.env.NODE_ENV !== 'production') {
const currentDirectory = getDirectory(import.meta.url)

streams.push({
level: 'trace',
level: config.log.level,
type: 'raw',
stream: new Writer({
basepath: join(currentDirectory, '..', '..'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ describe('middleware > defaultAuthentication', () => {
const request = {
user: 'test',
log: {
debug: vi.fn(),
trace: vi.fn(),
},
} as Request
const next = vi.fn()
Expand Down
4 changes: 3 additions & 1 deletion backend/test/services/log.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ describe('services > log', () => {
test('Writer > getAttributes', () => {
expect(Writer.getAttributes({ name: 'ignore', user: 'ignore' })).toBe('')
expect(Writer.getAttributes({ name: 'ignore', user: 'ignore', example: 'hello' })).toBe('example=hello')
expect(Writer.getAttributes({ id: true, url: true, method: true, 'response-time': true, status: true })).toBe('')
expect(Writer.getAttributes({ id: true, url: true, method: true, 'response-time': true, status: true })).toBe(
'id=true url=true method=true response-time=true status=true',
)
expect(Writer.getAttributes({ id: longId() })).toBe('')
})

Expand Down
2 changes: 1 addition & 1 deletion lib/python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ yolo = Model.create(
team_id="Uncategorised"
)

yolo.card_from_schema("minimal-general-v10-beta")
yolo.card_from_schema("minimal-general-v10")

# Create a new release
my_release = yolo.create_release(version="0.1.0",
Expand Down
Loading