IT技术博客大学习 共学习 共进步
全部 移动开发 后端 数据库 AI 算法 安全 DevOps 前端 设计 开发者

改造 Mojolicious 让日志显示当前模块和行号

扶凯 2014-06-10 12:23:43 累计浏览 2,175 次
本机暂存

原始显示

本着分享的精神, 给近一二年使用 Mojolicious 的经验分享给大家. 今天要分享的是怎么加强默认 Mojo 显示日志, 让我们更加好的排错, 默认显示的时候是下面这样:

[Mon Jun  9 18:40:06 2014] [debug] GET "/perldoc".
[Mon Jun  9 18:40:06 2014] [debug] Routing to a callback.
[Mon Jun  9 18:40:06 2014] [debug] Rendering inline template "0667de3944df7624273d6f814d01f4c9".
[Mon Jun  9 18:40:06 2014] [debug] Rendering inline template "4fcf2af99f1803a7a26c2e9b04430f8c".
[Mon Jun  9 18:40:06 2014] [debug] 200 OK (0.169724s, 5.892/s).

改造

有时我非常想知道, 这行日志到底是谁, 在哪打印出来的, 现在来让我们来实现这个功能, 如果是 Mojolicious::Lite

if( app->log->is_level('debug') ) { 
    nowarnings 'redefine';
    *Mojo::Log::_format = sub{
        my($self, $level, @lines) = @_; 
        my@caller= caller(4);
        my$caller= join' ', $caller[0], $caller[2];
        return'['. localtime(time) . "][$level] [$caller] ". join("\n", @lines). "\n";
    }   
}

如果是 Mojolicious 就给下列代码写到  startup 当中

if( $self->app->log->is_level('debug') ) { 
    nowarnings 'redefine';
    *Mojo::Log::_format = sub{
        my($self, $level, @lines) = @_; 
        my@caller= caller(4);
        my$caller= join' ', $caller[0], $caller[2];
        return'['. localtime(time) . "][$level] [$caller] ". join("\n", @lines). "\n";
    }   
}

最终效果

这样日志会显示成

[Mon Jun  9 18:35:47 2014][debug] [Mojolicious 107] GET "/perldoc".
[Mon Jun  9 18:35:47 2014][debug] [Mojolicious::Routes 119] Routing to a callback.
[Mon Jun  9 18:35:48 2014][debug] [Mojolicious::Plugin::EPLRenderer 34] Rendering inline template "0667de3944df7624273d6f814d01f4c9".
[Mon Jun  9 18:35:48 2014][debug] [Mojolicious::Plugin::EPLRenderer 34] Rendering inline template "4fcf2af99f1803a7a26c2e9b04430f8c".
[Mon Jun  9 18:35:48 2014][debug] [Mojolicious::Controller 210] 200 OK (0.171894s, 5.818/s).

象上面, 我们这样能清楚的知道是哪行, 那个函数打印了这个日志.

同分类推荐文章

  1. 等了十年的 Go 链式管道,终于来了:seq 让你像写 Scala 一样写 Go (2026-06-25 18:38:18)
  2. Go 实验特性详解 (2026-06-21 10:05:27)
  3. amd64 微架构级别对 Go 程序性能提升多少? (2026-06-21 09:38:49)

查看更多 后端 文章 →

建议继续学习

  1. Fix Bug的五个阶段 (累计阅读 42,972)
  2. 调试工具之GDB (累计阅读 14,828)
  3. gdb的基本工作原理是什么? (累计阅读 11,681)
  4. perl更新/修改/删除文本文件内容 (累计阅读 10,647)
  5. 深入理解Nginx之调试优化技巧 (累计阅读 8,225)
  6. Python 多进程日志记录 (累计阅读 7,839)
  7. perl大牛flw传说 (累计阅读 7,713)
  8. 内存越界的概念和调试方法 (累计阅读 7,275)
  9. AWStats是一个基于Perl的WEB日志分析工具。 (累计阅读 7,173)
  10. perl模块Getopt::Std用法及实例-从命令行读取参数模块 (累计阅读 7,017)