agentsclimarketplace

Structured logging

Skill ComeOnOliver/skillshub/skills/aiskillstore/marketplace/doyajin174/structured-logging

๐Ÿง  The right skill, one API call. AI agent skills registry with token-efficient skill resolution. 5,000+ skills from 500+ top repos.

Install
npx -y skills add ComeOnOliver/skillshub --skill structured-logging

Assembled from the repository path, not quoted from the project. Check it against their README if it does not work.

What its author says it does

Copied from the file, not written here

Implement JSON-based structured logging for observability. Use when setting up logging, debugging production issues, or preparing for log aggregation (ELK, Datadog). Covers log levels, context, and best practices.

The file declares its own license as MIT. That is the authorโ€™s claim about this one file, and it is not the same thing as the license GitHub reports for the repository, which is listed with the other numbers below.

SKILL.md

9.3 KB, as published. Nobody here has run it

Structured Logging

JSON ํฌ๋งท์˜ ๊ตฌ์กฐํ™”๋œ ๋กœ๊น…์„ ๊ตฌํ˜„ํ•˜๋Š” ์Šคํ‚ฌ์ž…๋‹ˆ๋‹ค.

Core Principle

"print๋ฌธ ๋Œ€์‹  ๊ตฌ์กฐํ™”๋œ ๋กœ๊ทธ๋ฅผ ๋‚จ๊ฒจ๋ผ." "๋กœ๊ทธ๋Š” ๊ฒ€์ƒ‰ ๊ฐ€๋Šฅํ•˜๊ณ , ์ง‘๊ณ„ ๊ฐ€๋Šฅํ•ด์•ผ ํ•œ๋‹ค."

์™œ Structured Logging์ธ๊ฐ€?

โŒ ์ผ๋ฐ˜ ํ…์ŠคํŠธ ๋กœ๊ทธ

[2024-01-15 10:30:45] ERROR User login failed for user123
[2024-01-15 10:30:46] INFO Processing request
  • ํŒŒ์‹ฑ ์–ด๋ ค์›€
  • ํ•„ํ„ฐ๋ง/๊ฒ€์ƒ‰ ์ œํ•œ
  • ์ปจํ…์ŠคํŠธ ์†์‹ค

โœ… ๊ตฌ์กฐํ™”๋œ ๋กœ๊ทธ (JSON)

{
  "timestamp": "2024-01-15T10:30:45.123Z",
  "level": "error",
  "message": "User login failed",
  "userId": "user123",
  "errorCode": "AUTH_INVALID_PASSWORD",
  "requestId": "req-abc-123",
  "duration": 45
}
  • ์‰ฌ์šด ํŒŒ์‹ฑ/๊ฒ€์ƒ‰
  • ํ•„๋“œ๋ณ„ ํ•„ํ„ฐ๋ง
  • ํ’๋ถ€ํ•œ ์ปจํ…์ŠคํŠธ

Log Levels

Level์šฉ๋„์˜ˆ์‹œ
fatal์‹œ์Šคํ…œ ์ข…๋ฃŒ ํ•„์š”DB ์—ฐ๊ฒฐ ์™„์ „ ์‹คํŒจ
error์—๋Ÿฌ ๋ฐœ์ƒ, ๋ณต๊ตฌ ๊ฐ€๋ŠฅAPI ํ˜ธ์ถœ ์‹คํŒจ
warn์ž ์žฌ์  ๋ฌธ์ œ์ง€์—ฐ๋œ ์‘๋‹ต
info์ฃผ์š” ์ด๋ฒคํŠธ์‚ฌ์šฉ์ž ๋กœ๊ทธ์ธ ์„ฑ๊ณต
debug๋””๋ฒ„๊น… ์ •๋ณดํ•จ์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ
trace์ƒ์„ธ ์ถ”์ ์‹คํ–‰ ํ๋ฆ„

ํ”„๋กœ๋•์…˜ ๋กœ๊ทธ ๋ ˆ๋ฒจ

ํ”„๋กœ๋•์…˜: info ์ด์ƒ๋งŒ
๊ฐœ๋ฐœ: debug ์ด์ƒ
๋””๋ฒ„๊น… ์‹œ: trace๊นŒ์ง€

ํ•„์ˆ˜ ๋กœ๊ทธ ํ•„๋“œ

interface LogEntry {
  // ํ•„์ˆ˜
  timestamp: string;    // ISO 8601
  level: string;        // error, warn, info, debug
  message: string;      // ์‚ฌ๋žŒ์ด ์ฝ์„ ์ˆ˜ ์žˆ๋Š” ๋ฉ”์‹œ์ง€

  // ๊ถŒ์žฅ
  requestId?: string;   // ์š”์ฒญ ์ถ”์ 
  userId?: string;      // ์‚ฌ์šฉ์ž ์‹๋ณ„
  service?: string;     // ์„œ๋น„์Šค๋ช…
  environment?: string; // prod, staging, dev

  // ์ƒํ™ฉ๋ณ„
  error?: {
    name: string;
    message: string;
    stack?: string;
  };
  duration?: number;    // ms
  metadata?: Record<string, unknown>;
}

Node.js ๊ตฌํ˜„

Pino (๊ถŒ์žฅ - ๊ณ ์„ฑ๋Šฅ)

npm install pino pino-pretty
// lib/logger.ts
import pino from 'pino';

export const logger = pino({
  level: process.env.LOG_LEVEL || 'info',

  // ๊ธฐ๋ณธ ํ•„๋“œ
  base: {
    service: 'my-app',
    environment: process.env.NODE_ENV,
  },

  // ํƒ€์ž„์Šคํƒฌํ”„ ํฌ๋งท
  timestamp: pino.stdTimeFunctions.isoTime,

  // ๊ฐœ๋ฐœ ํ™˜๊ฒฝ: pretty print
  transport: process.env.NODE_ENV === 'development'
    ? { target: 'pino-pretty' }
    : undefined,
});

// ์‚ฌ์šฉ
logger.info({ userId: '123' }, 'User logged in');
logger.error({ error, requestId }, 'Request failed');

Winston

npm install winston
// lib/logger.ts
import winston from 'winston';

export const logger = winston.createLogger({
  level: process.env.LOG_LEVEL || 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.errors({ stack: true }),
    winston.format.json()
  ),
  defaultMeta: {
    service: 'my-app',
    environment: process.env.NODE_ENV,
  },
  transports: [
    new winston.transports.Console({
      format: process.env.NODE_ENV === 'development'
        ? winston.format.combine(
            winston.format.colorize(),
            winston.format.simple()
          )
        : winston.format.json(),
    }),
  ],
});

Request Context

Request ID ์ „ํŒŒ

// middleware/requestId.ts
import { randomUUID } from 'crypto';
import { NextRequest, NextResponse } from 'next/server';

export function middleware(request: NextRequest) {
  const requestId = request.headers.get('x-request-id') || randomUUID();

  const response = NextResponse.next();
  response.headers.set('x-request-id', requestId);

  return response;
}

AsyncLocalStorage (๊ถŒ์žฅ)

// lib/context.ts
import { AsyncLocalStorage } from 'async_hooks';

interface RequestContext {
  requestId: string;
  userId?: string;
  startTime: number;
}

export const asyncLocalStorage = new AsyncLocalStorage<RequestContext>();

// ๋ฏธ๋“ค์›จ์–ด์—์„œ ์„ค์ •
export function withContext<T>(context: RequestContext, fn: () => T): T {
  return asyncLocalStorage.run(context, fn);
}

// ๋กœ๊ฑฐ์—์„œ ์‚ฌ์šฉ
export function getContext(): RequestContext | undefined {
  return asyncLocalStorage.getStore();
}

Context-aware Logger

// lib/logger.ts
import pino from 'pino';
import { getContext } from './context';

const baseLogger = pino({ /* config */ });

export const logger = {
  info: (obj: object, msg?: string) => {
    const ctx = getContext();
    baseLogger.info({ ...obj, ...ctx }, msg);
  },
  error: (obj: object, msg?: string) => {
    const ctx = getContext();
    baseLogger.error({ ...obj, ...ctx }, msg);
  },
  // ... other levels
};

๋กœ๊น… ํŒจํ„ด

API ์š”์ฒญ ๋กœ๊น…

// middleware/logging.ts
export async function loggingMiddleware(req: Request, handler: Function) {
  const startTime = Date.now();
  const requestId = randomUUID();

  logger.info({
    requestId,
    method: req.method,
    url: req.url,
    userAgent: req.headers.get('user-agent'),
  }, 'Request started');

  try {
    const response = await handler(req);

    logger.info({
      requestId,
      statusCode: response.status,
      duration: Date.now() - startTime,
    }, 'Request completed');

    return response;
  } catch (error) {
    logger.error({
      requestId,
      error: {
        name: error.name,
        message: error.message,
        stack: error.stack,
      },
      duration: Date.now() - startTime,
    }, 'Request failed');

    throw error;
  }
}

๋น„์ฆˆ๋‹ˆ์Šค ์ด๋ฒคํŠธ ๋กœ๊น…

// ์‚ฌ์šฉ์ž ํ™œ๋™
logger.info({
  event: 'user.login',
  userId,
  method: 'google_oauth',
  ip: request.ip,
}, 'User logged in');

// ๊ฒฐ์ œ
logger.info({
  event: 'payment.success',
  userId,
  amount: 9900,
  currency: 'KRW',
  paymentId,
}, 'Payment completed');

// ์—๋Ÿฌ
logger.error({
  event: 'payment.failed',
  userId,
  amount: 9900,
  errorCode: 'CARD_DECLINED',
  paymentId,
}, 'Payment failed');

์„ฑ๋Šฅ ๋กœ๊น…

async function fetchData() {
  const startTime = Date.now();

  try {
    const result = await db.query(/* ... */);

    logger.info({
      operation: 'db.query',
      table: 'users',
      duration: Date.now() - startTime,
      rowCount: result.length,
    }, 'Database query completed');

    return result;
  } catch (error) {
    logger.error({
      operation: 'db.query',
      table: 'users',
      duration: Date.now() - startTime,
      error: error.message,
    }, 'Database query failed');

    throw error;
  }
}

๊ธˆ์ง€ ํŒจํ„ด

// โŒ BAD: ๋ฏผ๊ฐ ์ •๋ณด ๋กœ๊น…
logger.info({ password, creditCard, ssn }, 'User data');

// โŒ BAD: ๊ณผ๋„ํ•œ ๋กœ๊น… (์„ฑ๋Šฅ ์ €ํ•˜)
for (const item of items) {
  logger.debug({ item }, 'Processing item');  // ์ˆ˜์ฒœ ๋ฒˆ ํ˜ธ์ถœ
}

// โŒ BAD: ๊ตฌ์กฐํ™”๋˜์ง€ ์•Š์€ ๋กœ๊ทธ
logger.info(`User ${userId} logged in at ${timestamp}`);

// โœ… GOOD: ๊ตฌ์กฐํ™”๋œ ๋กœ๊ทธ
logger.info({ userId, timestamp }, 'User logged in');

๋ฏผ๊ฐ ์ •๋ณด ์ œ๊ฑฐ

// lib/logger.ts
const sensitiveFields = ['password', 'token', 'apiKey', 'creditCard'];

function redactSensitiveData(obj: object): object {
  const redacted = { ...obj };

  for (const key of Object.keys(redacted)) {
    if (sensitiveFields.some(f => key.toLowerCase().includes(f))) {
      redacted[key] = '[REDACTED]';
    }
  }

  return redacted;
}

// Pino redact ์˜ต์…˜
const logger = pino({
  redact: ['password', 'creditCard', '*.token', 'headers.authorization'],
});

Log Aggregation ์—ฐ๋™

ELK Stack (Elasticsearch)

// filebeat.yml์—์„œ JSON ํŒŒ์‹ฑ
// ๋˜๋Š” ์ง์ ‘ Elasticsearch๋กœ ์ „์†ก
import { Client } from '@elastic/elasticsearch';

const esClient = new Client({ node: 'http://localhost:9200' });

const esTransport = new winston.transports.Stream({
  stream: {
    write: async (log: string) => {
      await esClient.index({
        index: 'app-logs',
        document: JSON.parse(log),
      });
    },
  },
});

Datadog

npm install dd-trace
// tracer.ts
import tracer from 'dd-trace';

tracer.init({
  service: 'my-app',
  env: process.env.NODE_ENV,
});

// ๋กœ๊ทธ์— trace ID ํฌํ•จ
logger.info({
  dd: {
    trace_id: tracer.scope().active()?.context().toTraceId(),
    span_id: tracer.scope().active()?.context().toSpanId(),
  },
}, 'Event with trace');

Checklist

์„ค์ •

  • ๊ตฌ์กฐํ™”๋œ ๋กœ๊น… ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์„ค์น˜ (Pino/Winston)
  • ๋กœ๊ทธ ๋ ˆ๋ฒจ ํ™˜๊ฒฝ๋ณ€์ˆ˜ ์„ค์ •
  • ๊ธฐ๋ณธ ํ•„๋“œ (service, environment) ์„ค์ •
  • Request ID ๋ฏธ๋“ค์›จ์–ด ์ ์šฉ
  • ๋ฏผ๊ฐ ์ •๋ณด redaction ์„ค์ •

๋กœ๊น… ํ‘œ์ค€

  • JSON ํฌ๋งท ์‚ฌ์šฉ
  • ์ ์ ˆํ•œ ๋กœ๊ทธ ๋ ˆ๋ฒจ ์‚ฌ์šฉ
  • ๋น„์ฆˆ๋‹ˆ์Šค ์ด๋ฒคํŠธ ๋กœ๊น…
  • ์—๋Ÿฌ์— ์Šคํƒ ํŠธ๋ ˆ์ด์Šค ํฌํ•จ
  • ์„ฑ๋Šฅ ์ธก์ • ๋กœ๊น…

์šด์˜

  • ๋กœ๊ทธ ์ง‘๊ณ„ ์‹œ์Šคํ…œ ์—ฐ๋™
  • ๋กœ๊ทธ ๊ธฐ๋ฐ˜ ์•Œ๋ฆผ ์„ค์ •
  • ๋กœ๊ทธ ๋ณด๊ด€ ์ •์ฑ… ์ˆ˜๋ฆฝ

References

Keep looking

Skills are one crate of 328,083. Ordering is by how many stacks a row turns up in, so the top of any crate is what has actually been picked rather than what has the most stars.