File size: 1,959 Bytes
f778c12 | 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 | /**
* Example hook handler: Log command lifecycle events to a file
*
* This handler demonstrates how to create a hook that logs emitted command events
* to a centralized log file for audit/debugging purposes.
*
* Enable this bundled hook with `openclaw hooks enable command-logger` or config:
*
* ```json
* {
* "hooks": {
* "internal": {
* "entries": {
* "command-logger": { "enabled": true }
* }
* }
* }
* }
* ```
*/
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { resolveStateDir } from "../../../config/paths.js";
import { formatErrorMessage } from "../../../infra/errors.js";
import { appendRegularFile } from "../../../infra/fs-safe.js";
import { createSubsystemLogger } from "../../../logging/subsystem.js";
import type { HookHandler } from "../../hooks.js";
const log = createSubsystemLogger("command-logger");
/**
* Log emitted command events to a file
*/
const logCommand: HookHandler = async (event) => {
// Only trigger on command events
if (event.type !== "command") {
return;
}
try {
// Create log directory
const stateDir = resolveStateDir(process.env, os.homedir);
const logDir = path.join(stateDir, "logs");
await fs.mkdir(logDir, { recursive: true });
// Append to command log file
const logFile = path.join(logDir, "commands.log");
const logLine =
JSON.stringify({
timestamp: event.timestamp.toISOString(),
action: event.action,
sessionKey: event.sessionKey,
senderId: event.context.senderId ?? "unknown",
source: event.context.commandSource ?? "unknown",
}) + "\n";
await appendRegularFile({
filePath: logFile,
content: logLine,
rejectSymlinkParents: true,
});
} catch (err) {
const message = formatErrorMessage(err);
log.error(`Failed to log command: ${message}`);
}
};
export default logCommand;
|