error_log是模块开发中唯一实时反馈核心行为的“运行时探针”,记录模块初始化失败、钩子未注册、配置解析中断、内存异常等关键信号,必须查看全局main块日志而非server块日志,结合模块名前缀可精准区分核心与第三方错误。

error_log 是模块扩展开发中唯一能实时反馈核心行为的“运行时探针”,它不记录业务逻辑,而是忠实输出 Nginx 内核与模块交互的关键信号——比如模块初始化失败、钩子函数未注册、配置解析中断、内存分配异常等。这些信息无法通过代码静态检查或单元测试捕获,必须依赖 error_log 在真实进程上下文中暴露。
定位模块加载失败的根本原因
当自定义模块编译后无法生效,常见表现是 reload 无报错但功能缺失。此时全局 error_log(main 块)会记录:
- “module ‘xxx’ not found” → 模块路径错误或未用 load_module 显式声明
- “failed to initialize module xxx: …” → init_master 或 init_module 回调中触发 panic 或返回非零值
- “directive ‘xxx’ is not supported” → 模块未正确注册指令,或指令名拼写/作用域不匹配
注意:这类错误只出现在 master 进程日志,worker 进程不会重复输出,因此必须查看全局 error_log 路径,而非 server 块内单独设置的日志文件。
验证模块生命周期与事件钩子执行
模块常需响应配置重载、worker 启动、连接建立等事件。设为 notice 或 info 级别后,error_log 可显示:
- “init cycle done”、“reconfiguring” → 表明 ngx_conf_parse 已完成,模块的 postconfiguration 钩子有机会执行
- “worker process is starting” → 对应模块的 init_worker 钩子是否被调用
- “http request processing started” → http 模块的 handler 钩子是否进入调度链
若某钩子完全无日志,说明其注册失败或被更高优先级模块拦截,需回查 ngx_http_add_handler 或 ngx_event_init 等注册逻辑。
捕获模块引发的 core 级异常
段错误、空指针解引用、非法内存访问等不会产生 HTTP 响应,但会在 error_log 中留下明确痕迹:
- “segmentation fault (core dumped)” → 直接提示崩溃,配合 ulimit -c unlimited + core_pattern 可生成 core dump
- “malloc(): corrupted unsorted chunks” → 内存管理错误,常见于模块中手动 malloc/free 不配对
- “*xx failed (12: Cannot allocate memory)” → 模块申请过大内存块,触发系统拒绝
这类日志总带进程 ID 和时间戳,结合 strace -p PID -e trace=brk,mmap 可快速确认是模块哪次内存操作越界。
区分核心模块与第三方模块错误源头
Nginx 日志默认在错误消息前标注模块名,例如:
- “[alert] 12345#67890: *1000 open() ‘/tmp/file’ failed (13: Permission denied) while sending response to client, client: …, server: …, request: …, host: …” → 未注明模块名,属核心 I/O 错误
- “[error] 12345#67890: *1001 lua entry thread aborted: runtime error: …” → 明确指向 ngx_http_lua_module
- “[crit] 12345#67890: *1002 redis module: connection timeout after 5000ms” → 第三方模块自定义错误前缀
开发新模块时,应在所有 ngx_log_error 调用中统一加前缀(如 “my_module: ”),避免与核心日志混淆,也便于 grep 快速过滤。











