PageRenderTime 30ms CodeModel.GetById 3ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Log/Log4perl/Appender/File.pm

http://github.com/mschilli/log4perl
Perl | 590 lines | 498 code | 78 blank | 14 comment | 41 complexity | 94d68aadce8f525cd36541d9ca4b2679 MD5 | raw file
  1. ##################################################
  2. package Log::Log4perl::Appender::File;
  3. ##################################################
  4. our @ISA = qw(Log::Log4perl::Appender);
  5. use warnings;
  6. use strict;
  7. use Log::Log4perl::Config::Watch;
  8. use Fcntl;
  9. use File::Path;
  10. use File::Spec::Functions qw(splitpath);
  11. use constant _INTERNAL_DEBUG => 0;
  12. use constant SYSWRITE_UTF8_OK => ( $] < 5.024 );
  13. ##################################################
  14. sub new {
  15. ##################################################
  16. my($class, @options) = @_;
  17. my $self = {
  18. name => "unknown name",
  19. umask => undef,
  20. owner => undef,
  21. group => undef,
  22. autoflush => 1,
  23. syswrite => 0,
  24. mode => "append",
  25. binmode => undef,
  26. utf8 => 0,
  27. recreate => 0,
  28. recreate_check_interval => 30,
  29. recreate_check_signal => undef,
  30. recreate_pid_write => undef,
  31. create_at_logtime => 0,
  32. header_text => undef,
  33. mkpath => 0,
  34. mkpath_umask => 0,
  35. @options,
  36. };
  37. if($self->{create_at_logtime}) {
  38. $self->{recreate} = 1;
  39. }
  40. for my $param ('umask', 'mkpath_umask') {
  41. if(defined $self->{$param} and $self->{$param} =~ /^0/) {
  42. # umask value is a string, meant to be an oct value
  43. $self->{$param} = oct($self->{$param});
  44. }
  45. }
  46. die "Mandatory parameter 'filename' missing" unless
  47. exists $self->{filename};
  48. bless $self, $class;
  49. if($self->{recreate_pid_write}) {
  50. print "Creating pid file",
  51. " $self->{recreate_pid_write}\n" if _INTERNAL_DEBUG;
  52. open FILE, ">$self->{recreate_pid_write}" or
  53. die "Cannot open $self->{recreate_pid_write}";
  54. print FILE "$$\n";
  55. close FILE;
  56. }
  57. print "Calling syswrite_encoder\n" if _INTERNAL_DEBUG;
  58. $self->{syswrite_encoder} = $self->syswrite_encoder();
  59. print "syswrite_encoder returned\n" if _INTERNAL_DEBUG;
  60. # This will die() if it fails
  61. $self->file_open() unless $self->{create_at_logtime};
  62. return $self;
  63. }
  64. ##################################################
  65. sub syswrite_encoder {
  66. ##################################################
  67. my($self) = @_;
  68. if( !SYSWRITE_UTF8_OK and $self->{syswrite} and $self->{utf8} ) {
  69. print "Requiring Encode\n" if _INTERNAL_DEBUG;
  70. eval { require Encode };
  71. print "Requiring Encode returned: $@\n" if _INTERNAL_DEBUG;
  72. if( $@ ) {
  73. die "syswrite and utf8 requires Encode.pm";
  74. } else {
  75. return sub { Encode::encode_utf8($_[0]) };
  76. }
  77. }
  78. return undef;
  79. }
  80. ##################################################
  81. sub filename {
  82. ##################################################
  83. my($self) = @_;
  84. return $self->{filename};
  85. }
  86. ##################################################
  87. sub file_open {
  88. ##################################################
  89. my($self) = @_;
  90. my $arrows = ">";
  91. my $sysmode = (O_CREAT|O_WRONLY);
  92. if($self->{mode} eq "append") {
  93. $arrows = ">>";
  94. $sysmode |= O_APPEND;
  95. } elsif ($self->{mode} eq "pipe") {
  96. $arrows = "|";
  97. } else {
  98. $sysmode |= O_TRUNC;
  99. }
  100. my $fh = do { local *FH; *FH; };
  101. my $didnt_exist = ! -e $self->{filename};
  102. if($didnt_exist && $self->{mkpath}) {
  103. my ($volume, $path, $file) = splitpath($self->{filename});
  104. if($path ne '' && !-e $path) {
  105. my $old_umask = umask($self->{mkpath_umask}) if defined $self->{mkpath_umask};
  106. my $options = {};
  107. foreach my $param (qw(owner group) ) {
  108. $options->{$param} = $self->{$param} if defined $self->{$param};
  109. }
  110. eval {
  111. mkpath($path,$options);
  112. };
  113. umask($old_umask) if defined $old_umask;
  114. die "Can't create path ${path} ($!)" if $@;
  115. }
  116. }
  117. my $old_umask = umask($self->{umask}) if defined $self->{umask};
  118. eval {
  119. if($self->{syswrite}) {
  120. sysopen $fh, "$self->{filename}", $sysmode or
  121. die "Can't sysopen $self->{filename} ($!)";
  122. } else {
  123. open $fh, "$arrows$self->{filename}" or
  124. die "Can't open $self->{filename} ($!)";
  125. }
  126. };
  127. umask($old_umask) if defined $old_umask;
  128. die $@ if $@;
  129. if($didnt_exist and
  130. ( defined $self->{owner} or defined $self->{group} )
  131. ) {
  132. eval { $self->perms_fix() };
  133. if($@) {
  134. # Cleanup and re-throw
  135. unlink $self->{filename};
  136. die $@;
  137. }
  138. }
  139. if($self->{recreate}) {
  140. $self->{watcher} = Log::Log4perl::Config::Watch->new(
  141. file => $self->{filename},
  142. (defined $self->{recreate_check_interval} ?
  143. (check_interval => $self->{recreate_check_interval}) : ()),
  144. (defined $self->{recreate_check_signal} ?
  145. (signal => $self->{recreate_check_signal}) : ()),
  146. );
  147. }
  148. $self->{fh} = $fh;
  149. if ($self->{autoflush} and ! $self->{syswrite}) {
  150. my $oldfh = select $self->{fh};
  151. $| = 1;
  152. select $oldfh;
  153. }
  154. if (defined $self->{binmode}) {
  155. binmode $self->{fh}, $self->{binmode};
  156. }
  157. if ($self->{utf8}) {
  158. # older perls can handle syswrite+utf8 just fine
  159. if(SYSWRITE_UTF8_OK or !$self->{syswrite}) {
  160. binmode $self->{fh}, ":utf8";
  161. }
  162. }
  163. if(defined $self->{header_text}) {
  164. if( $self->{header_text} !~ /\n\Z/ ) {
  165. $self->{header_text} .= "\n";
  166. }
  167. # quick and dirty print/syswrite without the usual
  168. # log() recreate magic.
  169. local $self->{recreate} = 0;
  170. $self->log( message => $self->{header_text} );
  171. }
  172. }
  173. ##################################################
  174. sub file_close {
  175. ##################################################
  176. my($self) = @_;
  177. if(defined $self->{fh}) {
  178. $self->close_with_care( $self->{ fh } );
  179. }
  180. undef $self->{fh};
  181. }
  182. ##################################################
  183. sub perms_fix {
  184. ##################################################
  185. my($self) = @_;
  186. my ($uid_org, $gid_org) = (stat $self->{filename})[4,5];
  187. my ($uid, $gid) = ($uid_org, $gid_org);
  188. if(!defined $uid) {
  189. die "stat of $self->{filename} failed ($!)";
  190. }
  191. my $needs_fixing = 0;
  192. if(defined $self->{owner}) {
  193. $uid = $self->{owner};
  194. if($self->{owner} !~ /^\d+$/) {
  195. $uid = (getpwnam($self->{owner}))[2];
  196. die "Unknown user: $self->{owner}" unless defined $uid;
  197. }
  198. }
  199. if(defined $self->{group}) {
  200. $gid = $self->{group};
  201. if($self->{group} !~ /^\d+$/) {
  202. $gid = getgrnam($self->{group});
  203. die "Unknown group: $self->{group}" unless defined $gid;
  204. }
  205. }
  206. if($uid != $uid_org or $gid != $gid_org) {
  207. chown($uid, $gid, $self->{filename}) or
  208. die "chown('$uid', '$gid') on '$self->{filename}' failed: $!";
  209. }
  210. }
  211. ##################################################
  212. sub file_switch {
  213. ##################################################
  214. my($self, $new_filename) = @_;
  215. print "Switching file from $self->{filename} to $new_filename\n" if
  216. _INTERNAL_DEBUG;
  217. $self->file_close();
  218. $self->{filename} = $new_filename;
  219. $self->file_open();
  220. }
  221. ##################################################
  222. sub log {
  223. ##################################################
  224. my($self, %params) = @_;
  225. # Warning: this function gets called by file_open() which assumes
  226. # it can use it as a simple print/syswrite wrapper by temporary
  227. # disabling the 'recreate' entry. Add anything fancy here and
  228. # fix up file_open() accordingly.
  229. if($self->{recreate}) {
  230. if($self->{recreate_check_signal}) {
  231. if(!$self->{watcher} or
  232. $self->{watcher}->{signal_caught}) {
  233. $self->file_switch($self->{filename});
  234. $self->{watcher}->{signal_caught} = 0;
  235. }
  236. } else {
  237. if(!$self->{watcher} or
  238. $self->{watcher}->file_has_moved()) {
  239. $self->file_switch($self->{filename});
  240. }
  241. }
  242. }
  243. my $fh = $self->{fh};
  244. if($self->{syswrite}) {
  245. my $rc =
  246. syswrite( $fh,
  247. $self->{ syswrite_encoder } ?
  248. $self->{ syswrite_encoder }->($params{message}) :
  249. $params{message} );
  250. if(!defined $rc) {
  251. die "Cannot syswrite to '$self->{filename}': $!";
  252. }
  253. } else {
  254. print $fh $params{message} or
  255. die "Cannot write to '$self->{filename}': $!";
  256. }
  257. }
  258. ##################################################
  259. sub DESTROY {
  260. ##################################################
  261. my($self) = @_;
  262. if ($self->{fh}) {
  263. my $fh = $self->{fh};
  264. $self->close_with_care( $fh );
  265. }
  266. }
  267. ###########################################
  268. sub close_with_care {
  269. ###########################################
  270. my( $self, $fh ) = @_;
  271. my $prev_rc = $?;
  272. my $rc = close $fh;
  273. # [rt #84723] If a sig handler is reaping the child generated
  274. # by close() internally before close() gets to it, it'll
  275. # result in a weird (but benign) error that we don't want to
  276. # expose to the user.
  277. if( !$rc ) {
  278. if( $self->{ mode } eq "pipe" and
  279. $!{ ECHILD } ) {
  280. if( $Log::Log4perl::CHATTY_DESTROY_METHODS ) {
  281. warn "$$: pipe closed with ECHILD error -- guess that's ok";
  282. }
  283. $? = $prev_rc;
  284. } else {
  285. warn "Can't close $self->{filename} ($!)";
  286. }
  287. }
  288. return $rc;
  289. }
  290. 1;
  291. __END__
  292. =encoding utf8
  293. =head1 NAME
  294. Log::Log4perl::Appender::File - Log to file
  295. =head1 SYNOPSIS
  296. use Log::Log4perl::Appender::File;
  297. my $app = Log::Log4perl::Appender::File->new(
  298. filename => 'file.log',
  299. mode => 'append',
  300. autoflush => 1,
  301. umask => 0222,
  302. );
  303. $file->log(message => "Log me\n");
  304. =head1 DESCRIPTION
  305. This is a simple appender for writing to a file.
  306. The C<log()> method takes a single scalar. If a newline character
  307. should terminate the message, it has to be added explicitly.
  308. Upon destruction of the object, the filehandle to access the
  309. file is flushed and closed.
  310. If you want to switch over to a different logfile, use the
  311. C<file_switch($newfile)> method which will first close the old
  312. file handle and then open a one to the new file specified.
  313. =head2 OPTIONS
  314. =over 4
  315. =item filename
  316. Name of the log file.
  317. =item mode
  318. Messages will be append to the file if C<$mode> is set to the
  319. string C<"append">. Will clobber the file
  320. if set to C<"clobber">. If it is C<"pipe">, the file will be understood
  321. as executable to pipe output to. Default mode is C<"append">.
  322. =item autoflush
  323. C<autoflush>, if set to a true value, triggers flushing the data
  324. out to the file on every call to C<log()>. C<autoflush> is on by default.
  325. =item syswrite
  326. C<syswrite>, if set to a true value, makes sure that the appender uses
  327. syswrite() instead of print() to log the message. C<syswrite()> usually
  328. maps to the operating system's C<write()> function and makes sure that
  329. no other process writes to the same log file while C<write()> is busy.
  330. Might safe you from having to use other synchronisation measures like
  331. semaphores (see: Synchronized appender).
  332. =item umask
  333. Specifies the C<umask> to use when creating the file, determining
  334. the file's permission settings.
  335. If set to C<0022> (default), new
  336. files will be created with C<rw-r--r--> permissions.
  337. If set to C<0000>, new files will be created with C<rw-rw-rw-> permissions.
  338. =item owner
  339. If set, specifies that the owner of the newly created log file should
  340. be different from the effective user id of the running process.
  341. Only makes sense if the process is running as root.
  342. Both numerical user ids and user names are acceptable.
  343. Log4perl does not attempt to change the ownership of I<existing> files.
  344. =item group
  345. If set, specifies that the group of the newly created log file should
  346. be different from the effective group id of the running process.
  347. Only makes sense if the process is running as root.
  348. Both numerical group ids and group names are acceptable.
  349. Log4perl does not attempt to change the group membership of I<existing> files.
  350. =item utf8
  351. If you're printing out Unicode strings, the output filehandle needs
  352. to be set into C<:utf8> mode:
  353. my $app = Log::Log4perl::Appender::File->new(
  354. filename => 'file.log',
  355. mode => 'append',
  356. utf8 => 1,
  357. );
  358. =item binmode
  359. To manipulate the output filehandle via C<binmode()>, use the
  360. binmode parameter:
  361. my $app = Log::Log4perl::Appender::File->new(
  362. filename => 'file.log',
  363. mode => 'append',
  364. binmode => ":utf8",
  365. );
  366. A setting of ":utf8" for C<binmode> is equivalent to specifying
  367. the C<utf8> option (see above).
  368. =item recreate
  369. Normally, if a file appender logs to a file and the file gets moved to
  370. a different location (e.g. via C<mv>), the appender's open file handle
  371. will automatically follow the file to the new location.
  372. This may be undesirable. When using an external logfile rotator,
  373. for example, the appender should create a new file under the old name
  374. and start logging into it. If the C<recreate> option is set to a true value,
  375. C<Log::Log4perl::Appender::File> will do exactly that. It defaults to
  376. false. Check the C<recreate_check_interval> option for performance
  377. optimizations with this feature.
  378. =item recreate_check_interval
  379. In C<recreate> mode, the appender has to continuously check if the
  380. file it is logging to is still in the same location. This check is
  381. fairly expensive, since it has to call C<stat> on the file name and
  382. figure out if its inode has changed. Doing this with every call
  383. to C<log> can be prohibitively expensive. Setting it to a positive
  384. integer value N will only check the file every N seconds. It defaults to 30.
  385. This obviously means that the appender will continue writing to
  386. a moved file until the next check occurs, in the worst case
  387. this will happen C<recreate_check_interval> seconds after the file
  388. has been moved or deleted. If this is undesirable,
  389. setting C<recreate_check_interval> to 0 will have the
  390. appender check the file with I<every> call to C<log()>.
  391. =item recreate_check_signal
  392. In C<recreate> mode, if this option is set to a signal name
  393. (e.g. "USR1"), the appender will recreate a missing logfile
  394. when it receives the signal. It uses less resources than constant
  395. polling. The usual limitation with perl's signal handling apply.
  396. Check the FAQ for using this option with the log rotating
  397. utility C<newsyslog>.
  398. =item recreate_pid_write
  399. The popular log rotating utility C<newsyslog> expects a pid file
  400. in order to send the application a signal when its logs have
  401. been rotated. This option expects a path to a file where the pid
  402. of the currently running application gets written to.
  403. Check the FAQ for using this option with the log rotating
  404. utility C<newsyslog>.
  405. =item create_at_logtime
  406. The file appender typically creates its logfile in its constructor, i.e.
  407. at Log4perl C<init()> time. This is desirable for most use cases, because
  408. it makes sure that file permission problems get detected right away, and
  409. not after days/weeks/months of operation when the appender suddenly needs
  410. to log something and fails because of a problem that was obvious at
  411. startup.
  412. However, there are rare use cases where the file shouldn't be created
  413. at Log4perl C<init()> time, e.g. if the appender can't be used by the current
  414. user although it is defined in the configuration file. If you set
  415. C<create_at_logtime> to a true value, the file appender will try to create
  416. the file at log time. Note that this setting lets permission problems
  417. sit undetected until log time, which might be undesirable.
  418. =item header_text
  419. If you want Log4perl to print a header into every newly opened
  420. (or re-opened) logfile, set C<header_text> to either a string
  421. or a subroutine returning a string. If the message doesn't have a newline,
  422. a newline at the end of the header will be provided.
  423. =item mkpath
  424. If this this option is set to true,
  425. the directory path will be created if it does not exist yet.
  426. =item mkpath_umask
  427. Specifies the C<umask> to use when creating the directory, determining
  428. the directory's permission settings.
  429. If set to C<0022> (default), new
  430. directory will be created with C<rwxr-xr-x> permissions.
  431. If set to C<0000>, new directory will be created with C<rwxrwxrwx> permissions.
  432. =back
  433. Design and implementation of this module has been greatly inspired by
  434. Dave Rolsky's C<Log::Dispatch> appender framework.
  435. =head1 LICENSE
  436. Copyright 2002-2013 by Mike Schilli E<lt>m@perlmeister.comE<gt>
  437. and Kevin Goess E<lt>cpan@goess.orgE<gt>.
  438. This library is free software; you can redistribute it and/or modify
  439. it under the same terms as Perl itself.
  440. =head1 AUTHOR
  441. Please contribute patches to the project on Github:
  442. http://github.com/mschilli/log4perl
  443. Send bug reports or requests for enhancements to the authors via our
  444. MAILING LIST (questions, bug reports, suggestions/patches):
  445. log4perl-devel@lists.sourceforge.net
  446. Authors (please contact them via the list above, not directly):
  447. Mike Schilli <m@perlmeister.com>,
  448. Kevin Goess <cpan@goess.org>
  449. Contributors (in alphabetical order):
  450. Ateeq Altaf, Cory Bennett, Jens Berthold, Jeremy Bopp, Hutton
  451. Davidson, Chris R. Donnelly, Matisse Enzer, Hugh Esco, Anthony
  452. Foiani, James FitzGibbon, Carl Franks, Dennis Gregorovic, Andy
  453. Grundman, Paul Harrington, Alexander Hartmaier David Hull,
  454. Robert Jacobson, Jason Kohles, Jeff Macdonald, Markus Peter,
  455. Brett Rann, Peter Rabbitson, Erik Selberg, Aaron Straup Cope,
  456. Lars Thegler, David Viner, Mac Yang.