Improve logging system with environment variable control

- Change default log level to 'warn' for production
- Add PAYLOAD_AUTOMATION_LOG_LEVEL environment variable
- Remove all verbose config-phase logs
- Add documentation for log level control
This commit is contained in:
2025-09-09 13:52:06 +02:00
parent e138176878
commit 73c8c20c4b
4 changed files with 55 additions and 21 deletions

View File

@@ -155,6 +155,34 @@ Use JSONPath to access workflow data:
- Node.js ^18.20.2 || >=20.9.0 - Node.js ^18.20.2 || >=20.9.0
- pnpm ^9 || ^10 - pnpm ^9 || ^10
## Environment Variables
Control plugin logging with these environment variables:
### `PAYLOAD_AUTOMATION_LOG_LEVEL`
Controls both configuration-time and runtime logging.
- **Values**: `silent`, `error`, `warn`, `info`, `debug`, `trace`
- **Default**: `warn`
- **Example**: `PAYLOAD_AUTOMATION_LOG_LEVEL=debug`
### `PAYLOAD_AUTOMATION_CONFIG_LOG_LEVEL` (optional)
Override log level specifically for configuration-time logs (plugin setup).
- **Values**: Same as above
- **Default**: Falls back to `PAYLOAD_AUTOMATION_LOG_LEVEL` or `warn`
- **Example**: `PAYLOAD_AUTOMATION_CONFIG_LOG_LEVEL=silent`
### Production Usage
For production, keep the default (`warn`) or use `error` or `silent`:
```bash
PAYLOAD_AUTOMATION_LOG_LEVEL=error npm start
```
### Development Usage
For debugging, use `debug` or `info`:
```bash
PAYLOAD_AUTOMATION_LOG_LEVEL=debug npm run dev
```
## Documentation ## Documentation
Full documentation coming soon. For now, explore the development environment in the repository for examples and patterns. Full documentation coming soon. For now, explore the development environment in the repository for examples and patterns.

View File

@@ -145,7 +145,6 @@ export const workflowsPlugin =
// CRITICAL: Modify existing collection configs BEFORE PayloadCMS processes them // CRITICAL: Modify existing collection configs BEFORE PayloadCMS processes them
// This is the ONLY time we can add hooks that will actually work // This is the ONLY time we can add hooks that will actually work
const logger = getConfigLogger() const logger = getConfigLogger()
logger.debug('Modifying collection configs...')
if (config.collections && pluginOptions.collectionTriggers) { if (config.collections && pluginOptions.collectionTriggers) {
for (const [triggerSlug, triggerConfig] of Object.entries(pluginOptions.collectionTriggers)) { for (const [triggerSlug, triggerConfig] of Object.entries(pluginOptions.collectionTriggers)) {
@@ -159,7 +158,6 @@ export const workflowsPlugin =
} }
const collection = config.collections[collectionIndex] const collection = config.collections[collectionIndex]
logger.debug(`Found collection '${triggerSlug}' - modifying its hooks...`)
// Initialize hooks if needed // Initialize hooks if needed
if (!collection.hooks) { if (!collection.hooks) {
@@ -266,7 +264,6 @@ export const workflowsPlugin =
// Add the hook to the collection config // Add the hook to the collection config
collection.hooks.afterChange.push(automationHook) collection.hooks.afterChange.push(automationHook)
logger.debug(`Added automation hook to '${triggerSlug}' - hook count: ${collection.hooks.afterChange.length}`)
} }
} }
@@ -275,17 +272,13 @@ export const workflowsPlugin =
} }
const configLogger = getConfigLogger() const configLogger = getConfigLogger()
configLogger.debug(`Configuring workflow plugin with ${Object.keys(pluginOptions.collectionTriggers || {}).length} collection triggers`)
// Generate cron tasks for workflows with cron triggers // Generate cron tasks for workflows with cron triggers
generateCronTasks(config) generateCronTasks(config)
for (const step of pluginOptions.steps) { for (const step of pluginOptions.steps) {
if (!config.jobs?.tasks?.find(task => task.slug === step.slug)) { if (!config.jobs?.tasks?.find(task => task.slug === step.slug)) {
configLogger.debug(`Registering task: ${step.slug}`)
config.jobs?.tasks?.push(step) config.jobs?.tasks?.push(step)
} else {
configLogger.debug(`Task ${step.slug} already registered, skipping`)
} }
} }
@@ -295,11 +288,9 @@ export const workflowsPlugin =
// Set up onInit to register collection hooks and initialize features // Set up onInit to register collection hooks and initialize features
const incomingOnInit = config.onInit const incomingOnInit = config.onInit
config.onInit = async (payload) => { config.onInit = async (payload) => {
configLogger.info(`onInit called - collections: ${Object.keys(payload.collections).length}`)
// Execute any existing onInit functions first // Execute any existing onInit functions first
if (incomingOnInit) { if (incomingOnInit) {
configLogger.debug('Executing existing onInit function')
await incomingOnInit(payload) await incomingOnInit(payload)
} }

View File

@@ -7,7 +7,6 @@ export function initWebhookEndpoint(config: Config, webhookPrefix = 'webhook'):
const logger = getConfigLogger() const logger = getConfigLogger()
// Ensure the prefix starts with a slash // Ensure the prefix starts with a slash
const normalizedPrefix = webhookPrefix.startsWith('/') ? webhookPrefix : `/${webhookPrefix}` const normalizedPrefix = webhookPrefix.startsWith('/') ? webhookPrefix : `/${webhookPrefix}`
logger.debug(`Adding webhook endpoint: ${normalizedPrefix}`)
// Define webhook endpoint // Define webhook endpoint
const webhookEndpoint = { const webhookEndpoint = {
@@ -170,9 +169,5 @@ export function initWebhookEndpoint(config: Config, webhookPrefix = 'webhook'):
if (!existingEndpoint) { if (!existingEndpoint) {
// Combine existing endpoints with the webhook endpoint // Combine existing endpoints with the webhook endpoint
config.endpoints = [...(config.endpoints || []), webhookEndpoint] config.endpoints = [...(config.endpoints || []), webhookEndpoint]
logger.debug(`Webhook endpoint added at path: ${webhookEndpoint.path}`)
logger.debug('Webhook endpoint added')
} else {
logger.debug(`Webhook endpoint already exists at path: ${webhookEndpoint.path}`)
} }
} }

View File

@@ -3,25 +3,40 @@ import type { Payload } from 'payload'
// Global logger instance - use Payload's logger type // Global logger instance - use Payload's logger type
let pluginLogger: null | Payload['logger'] = null let pluginLogger: null | Payload['logger'] = null
/**
* Get the configured log level from environment variables
* Supports: PAYLOAD_AUTOMATION_LOG_LEVEL for unified control
* Or separate: PAYLOAD_AUTOMATION_CONFIG_LOG_LEVEL and PAYLOAD_AUTOMATION_LOG_LEVEL
*/
function getConfigLogLevel(): string {
return process.env.PAYLOAD_AUTOMATION_CONFIG_LOG_LEVEL ||
process.env.PAYLOAD_AUTOMATION_LOG_LEVEL ||
'warn' // Default to warn level for production
}
/** /**
* Simple config-time logger for use during plugin configuration * Simple config-time logger for use during plugin configuration
* Uses console with plugin prefix since Payload logger isn't available yet * Uses console with plugin prefix since Payload logger isn't available yet
*/ */
const configLogger = { const configLogger = {
debug: <T>(message: string, ...args: T[]) => { debug: <T>(message: string, ...args: T[]) => {
if (!process.env.PAYLOAD_AUTOMATION_CONFIG_LOGGING) {return} const level = getConfigLogLevel()
console.log(`[payload-automation] ${message}`, ...args) if (level === 'silent' || (level !== 'debug' && level !== 'trace')) {return}
console.debug(`[payload-automation] ${message}`, ...args)
}, },
error: <T>(message: string, ...args: T[]) => { error: <T>(message: string, ...args: T[]) => {
if (!process.env.PAYLOAD_AUTOMATION_CONFIG_LOGGING) {return} const level = getConfigLogLevel()
if (level === 'silent') {return}
console.error(`[payload-automation] ${message}`, ...args) console.error(`[payload-automation] ${message}`, ...args)
}, },
info: <T>(message: string, ...args: T[]) => { info: <T>(message: string, ...args: T[]) => {
if (!process.env.PAYLOAD_AUTOMATION_CONFIG_LOGGING) {return} const level = getConfigLogLevel()
console.log(`[payload-automation] ${message}`, ...args) if (level === 'silent' || level === 'error' || level === 'warn') {return}
console.info(`[payload-automation] ${message}`, ...args)
}, },
warn: <T>(message: string, ...args: T[]) => { warn: <T>(message: string, ...args: T[]) => {
if (!process.env.PAYLOAD_AUTOMATION_CONFIG_LOGGING) {return} const level = getConfigLogLevel()
if (level === 'silent' || level === 'error') {return}
console.warn(`[payload-automation] ${message}`, ...args) console.warn(`[payload-automation] ${message}`, ...args)
} }
} }
@@ -39,8 +54,13 @@ export function getConfigLogger() {
*/ */
export function initializeLogger(payload: Payload): Payload['logger'] { export function initializeLogger(payload: Payload): Payload['logger'] {
// Create a child logger with plugin identification // Create a child logger with plugin identification
// Use PAYLOAD_AUTOMATION_LOG_LEVEL as the primary env var
const logLevel = process.env.PAYLOAD_AUTOMATION_LOG_LEVEL ||
process.env.PAYLOAD_AUTOMATION_LOGGING || // Legacy support
'warn' // Default to warn level for production
pluginLogger = payload.logger.child({ pluginLogger = payload.logger.child({
level: process.env.PAYLOAD_AUTOMATION_LOGGING || 'silent', level: logLevel,
plugin: '@xtr-dev/payload-automation' plugin: '@xtr-dev/payload-automation'
}) })
return pluginLogger return pluginLogger