Log.pm 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package Trog::Log;
  2. use strict;
  3. use warnings;
  4. use POSIX qw{strftime};
  5. use Log::Dispatch;
  6. use Log::Dispatch::Screen;
  7. use Log::Dispatch::FileRotate;
  8. use Exporter 'import';
  9. our @EXPORT_OK = qw{is_debug INFO DEBUG WARN FATAL};
  10. our %EXPORT_TAGS = ( 'all' => \@EXPORT_OK );
  11. my $LOGNAME = -d '/var/log' ? '/var/log/www/tcms.log' : '~/.tcms/tcms.log';
  12. $LOGNAME = $ENV{CUSTOM_LOG} if $ENV{CUSTOM_LOG};
  13. my $LEVEL = $ENV{WWW_VERBOSE} ? 'debug' : 'info';
  14. # By default only log requests & warnings.
  15. # Otherwise emit debug messages.
  16. my $rotate = Log::Dispatch::FileRotate->new(
  17. name => 'tcms',
  18. filename => $LOGNAME,
  19. min_level => $LEVEL,
  20. 'mode' => 'append',
  21. size => 10 * 1024 * 1024,
  22. max => 6,
  23. );
  24. # Only send fatal events/errors to prod-web.log
  25. my $screen = Log::Dispatch::Screen->new(
  26. name => 'screen',
  27. min_level => 'error',
  28. );
  29. our $log = Log::Dispatch->new();
  30. $log->add($rotate);
  31. $log->add($screen);
  32. uuid("INIT");
  33. DEBUG("If you see this message, you are running in DEBUG mode. Turn off WWW_VERBOSE env var if you are running in production.");
  34. uuid("BEGIN");
  35. #memoize
  36. my $rq;
  37. sub is_debug {
  38. return $LEVEL eq 'debug';
  39. }
  40. sub uuid {
  41. my $requestid = shift;
  42. $rq = $requestid if $requestid;
  43. $requestid //= return $rq;
  44. }
  45. #XXX make perl -c quit whining
  46. BEGIN {
  47. our $user;
  48. $Trog::Log::user = 'nobody';
  49. $Trog::Log::ip = '0.0.0.0';
  50. }
  51. sub _log {
  52. my ( $msg, $level ) = @_;
  53. $msg //= "No message passed. This is almost certainly a bug. ";
  54. my $tstamp = strftime "%a %b %d %T %Y", localtime;
  55. my $uuid = uuid();
  56. return "[$level]: <$tstamp> {Request $uuid} $Trog::Log::ip |$Trog::Log::user| $msg\n";
  57. }
  58. sub DEBUG {
  59. $log->debug( _log( shift, 'DEBUG' ) );
  60. }
  61. sub INFO {
  62. $log->info( _log( shift, 'INFO' ) );
  63. }
  64. sub WARN {
  65. $log->warning( _log( shift, 'WARN' ) );
  66. }
  67. sub FATAL {
  68. $log->log_and_die( level => 'error', message => _log( shift, 'FATAL' ) );
  69. }
  70. 1;