
api-logging-guidelines
Best practices and guidelines for using logger in API routes. Defines appropriate logging levels, what to log, and when to avoid logging. Use when implementing or reviewing API route logging, debugging strategies, or optimizing log output.
- Installs
- 52
- Last 24h
- —
- Trending rank
- —
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/inkeep/agents --skill api-logging-guidelines- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads api-logging-guidelines automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
API Route Logging Guidelines
Comprehensive guidance for appropriate use of logging in API routes to maintain clean, useful, and performant logs.
Core Principles
1. Avoid Redundant Logging
DON'T log what's already logged by middleware:
// ❌ BAD - Request details are already logged by middleware
logger.info({ tenantId, projectId }, 'Getting project details');
DO rely on request middleware logging:
- Request/response middleware already logs: method, path, status, duration, path params
- These logs include tenant/project IDs from the URL path
- Adding duplicate logs creates noise without value
2. Log Level Guidelines
| Level | Use Case | Examples |
|---|---|---|
| ERROR | Unexpected failures requiring attention | Database connection failures, unhandled exceptions, critical service errors |
| WARN | Recoverable issues or concerning patterns | Rate limiting triggered, deprecated API usage, fallback behavior activated |
| INFO | Important business events (NOT routine operations) | User account created, payment processed, critical configuration changed |
| DEBUG | Detailed diagnostic information | Query parameters, intermediate calculations, cache hit/miss details |
3. What TO Log
Log these important events:
// ✅ GOOD - Important business event
logger.info({
userId,
oldPlan: 'free',
newPlan: 'pro',
mrr: 99
}, 'User upgraded subscription');
// ✅ GOOD - Error with context
logger.error({
error,
tenantId,
webhookUrl,
attemptNumber: 3
}, 'Webhook delivery failed after retries');
// ✅ GOOD - Security-relevant event
logger.warn({
ip: c.req.header('x-forwarded-for'),
userId,
attemptedResource
}, 'Unauthorized access attempt');
// ✅ GOOD - Performance issue
logger.warn({
duration: 5234,
query,
resultCount: 10000
}, 'Slow query detected');
4. What NOT to Log
Avoid logging routine operations:
// ❌ BAD - Routine CRUD operation
logger.info('Getting user by ID');
// ❌ BAD - Already logged by middleware
logger.info(`Processing GET request to /api/users/${id}`);
// ❌ BAD - No actionable information
logger.info('Starting database query');
// ❌ BAD - Sensitive information
logger.info({ password, apiKey }, 'User login attempt');
// ❌ BAD - Overly granular
logger.debug('Entering function processUser');
logger.debug('Exiting function processUser');
API Route Patterns
Pattern 1: Error Handling
// ✅ GOOD - Log errors with context
export const route = router.get('/:id', async (c) => {
try {
const result = await riskyOperation();
return c.json(result);
} catch (error) {
// Log error with relevant context
logger.error({
error,
userId: c.get('userId'),
operation: 'riskyOperation',
// Include any relevant debugging context
requestId: c.get('requestId')
}, 'Operation failed');
// Return generic error to client (don't leak internals)
return c.json({ error: 'Internal server error' }, 500);
}
});
Pattern 2: Business Events
// ✅ GOOD - Log significant business events
export const route = router.post('/subscription/upgrade', async (c) => {
const { planId } = await c.req.json();
const result = await upgradeSubscription(userId, planId);
// This is worth logging - it's a significant business event
logger.info({
userId,
oldPlan: result.previousPlan,
newPlan: result.newPlan,
mrr: result.mrr,
timestamp: new Date().toISOString()
}, 'Subscription upgraded');
return c.json(result);
});
Pattern 3: Performance Monitoring
// ✅ GOOD - Log performance issues
export const route = router.get('/search', async (c) => {
const start = Date.now();
const results = await performSearch(query);
const duration = Date.now() - start;
// Only log if performance is concerning
if (duration > 1000) {
logger.warn({
duration,
query,
resultCount: results.length,
cached: false
}, 'Slow search query');
}
return c.json(results);
});
Pattern 4: Security Events
// ✅ GOOD - Log security-relevant events
export const route = router.post('/api/admin/*', async (c) => {
const hasPermission = await checkPermission(userId, resource);
if (!hasPermission) {
// Log unauthorized access attempts
logger.warn({
userId,
resource,
ip: c.req.header('x-forwarded-for'),
userAgent: c.req.header('user-agent')
}, 'Unauthorized access attempt');
return c.json({ error: 'Forbidden' }, 403);
}
// Proceed with authorized request...
});
Environment-Specific Guidelines
Development
// More verbose logging acceptable in development
if (process.env.NODE_ENV === 'development') {
logger.debug({ params, body }, 'Request details');
}
Production
- Minimize INFO level logs to important events only
- Never log sensitive data (passwords, tokens, keys, PII)
- Use structured logging for better searchability
- Include correlation IDs for tracing requests
Migration Strategy
When refactoring existing verbose logging:
- Identify redundant logs: Remove logs that duplicate middleware logging
- Downgrade routine operations: Move routine operations from INFO to DEBUG
- Enhance error logs: Add more context to error logs
- Add business event logs: Ensure important business events are logged
- Review log levels: Ensure each log uses the appropriate level
Before:
router.get('/:id', async (c) => {
const { id } = c.req.param();
logger.info({ id }, 'Getting item by ID'); // Redundant
const item = await getItem(id);
logger.info({ item }, 'Retrieved item'); // Too verbose
return c.json(item);
});
After:
router.get('/:id', async (c) => {
const { id } = c.req.param();
try {
const item = await getItem(id);
// No logging needed - routine successful operation
return c.json(item);
} catch (error) {
// Only log errors
logger.error({ error, id }, 'Failed to retrieve item');
return c.json({ error: 'Item not found' }, 404);
}
});
Debugging Without Verbose Logs
Instead of verbose logging, use these strategies:
- Use debug mode selectively: Enable DEBUG level for specific modules when troubleshooting
- Use tracing: OpenTelemetry/Jaeger for distributed tracing
- Use metrics: Prometheus/StatsD for performance metrics
- Use error tracking: Sentry/Rollbar for error aggregation
- Use feature flags: Enable verbose logging for specific users/requests when debugging
Summary Checklist
Before adding a log statement, ask:
- Is this already logged by middleware? (method, path, status, params)
- Is this a significant business event or just routine operation?
- Does this log provide actionable information?
- Am I using the correct log level?
- Am I including helpful context without sensitive data?
- Will this log be useful in production or just create noise?
Remember: Good logging is about signal, not volume. Every log should serve a purpose.
FAQ
What does the api-logging-guidelines skill do?
Best practices and guidelines for using logger in API routes. Defines appropriate logging levels, what to log, and when to avoid logging. Use when implementing or reviewing API route logging, debugging strategies, or optimizing log output.
How do I install api-logging-guidelines?
Run npx skills add https://github.com/inkeep/agents --skill api-logging-guidelines in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/api-logging-guidelines/ (personal) or .claude/skills/api-logging-guidelines/ (project).
Which AI agents can use api-logging-guidelines?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is api-logging-guidelines safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains api-logging-guidelines?
It is published by inkeep in inkeep/agents. It has 52 recorded installs.
More from inkeep/agents
adding-env-variables
inkeep/agents
Guide for adding new environment variables to the codebase. Ensures env.ts schemas include descriptions and .env.example is kept in sync. Triggers on: add env variable, new environment variable, env.ts change, add config variable, INKEEP, adding to .env.
data-model-changes
inkeep/agents
Guide for making changes to the database schema, validation, types, and data access layer. Use when adding tables, columns, relations, or modifying the data model. Triggers on: add table, add column, modify schema, database change, data model, new entity, schema migration.
Popular devops & cloud skills
microsoft-foundry
microsoft/azure-skills
Build, deploy, evaluate, optimize, fine-tune, and manage Microsoft Foundry agents, models, and resources end to end. USE FOR: foundry, azd ai agent, azd provision/deploy, hosted agent scaffold/develop/run/deploy/troubleshoot, prompt agent create, managed harness agent create, GitHub Copilot harness agent, create agent, update agent, add tool to agent, invoke agent, agent insights, evaluate agent, batch eval, continuous eval, continuous monitoring, agent CI/CD, optimize prompt, improve prompt, optimize agent instructions, Agent Optimizer scaffold, dataset curation from traces, deploy model, model fine-tuning (SFT/DPO/RFT), Foundry project, RBAC, role assignment, permissions, quota, capacity, region, deployment failure, AI Services, create Foundry resource, knowledge index, customize deployment, onboard, availability, training-data, grader, distillation, large file upload. DO NOT USE FOR: Azure Functions, App Service, general Azure deploy (use azure-deploy), general Azure prep (use azure
azure-diagnostics
microsoft/azure-skills
Debug Azure production issues on Azure using AppLens, Azure Monitor, resource health, and safe triage. WHEN: debug production issues, troubleshoot app service, app service high CPU, app service deployment failure, troubleshoot container apps, container app 503 or target port mismatch, troubleshoot functions, function telemetry missing or stopped after a config/connection-string change, troubleshoot AKS, VM RDP, Linux SSH, VM black screen, can't connect to VM, reset VM password, NSG or firewall blocking, kubectl cannot connect, kube-system/CoreDNS failures, pod pending, crashloop, node not ready, upgrade failures, analyze logs, KQL, insights, image pull failures, cold start issues, health probe failures, resource health, root cause of errors, troubleshoot event hubs, troubleshoot service bus, messaging SDK error, AMQP connection failure, message lock lost, lock renewal during long-running processing, service bus dead letter.
azure-prepare
microsoft/azure-skills
Prepare azd-based Azure projects for deployment: generates azure.yaml, infrastructure (Bicep/Terraform), and Dockerfiles for the Azure Developer CLI (azd) workflow. USE ONLY when the user explicitly wants to use azd as the deployment tool, or the project already has an azure.yaml file. DO NOT USE FOR: non-azd deployments, Python App Service code-only deploys (use python-appservice-deploy), or cross-cloud migration (use azure-cloud-migrate). WHEN: prepare app for azd, create azure.yaml, set up azd infrastructure, modernize app for Azure with azd, deploy with azd, function app, timer trigger, service bus trigger, event-driven function, managed identity, generate Bicep, generate Terraform, create and deploy to Azure.
azure-ai
microsoft/azure-skills
Use for Azure AI: Search, Speech, OpenAI, Document Intelligence. Helps with search, vector/hybrid search, speech-to-text, text-to-speech, transcription, OCR. WHEN: AI Search, query search, vector search, hybrid search, semantic search, speech-to-text, text-to-speech, transcribe, OCR, convert text to speech.
azure-deploy
microsoft/azure-skills
Execute Azure deployments for ALREADY-PREPARED applications that have existing .azure/deployment-plan.md and infrastructure files. DO NOT use this skill when the user asks to CREATE a new application — use azure-prepare instead. This skill runs azd up, azd deploy, terraform apply, and az deployment commands with built-in error recovery. Requires .azure/deployment-plan.md from azure-prepare and validated status from azure-validate. WHEN: "run azd up", "run azd deploy", "execute deployment", "push to production", "push to cloud", "go live", "ship it", "bicep deploy", "terraform apply", "publish to Azure", "launch on Azure". DO NOT USE WHEN: "create and deploy", "build and deploy", "create a new app", "set up infrastructure", "create and deploy to Azure using Terraform" — use azure-prepare for these.
azure-validate
microsoft/azure-skills
Pre-deployment validation for Azure readiness. Run deep checks on configuration, infrastructure (Bicep or Terraform), RBAC role assignments, managed identity permissions, and prerequisites before deploying. WHEN: validate my app, check deployment readiness, run preflight checks, verify configuration, check if ready to deploy, validate azure.yaml, validate Bicep, test before deploying, troubleshoot deployment errors, validate Azure Functions, validate function app, validate serverless deployment, verify RBAC roles, check role assignments, review managed identity permissions, what-if analysis, validate Container Apps deployment.