linux – 旋转愚蠢的非交互式应用程序的日志

Ubuntu 10.4服务器.

我有一个愚蠢的非交互式遗留服务,它在我的服务器上不断运行.

它将其日志写入具有固定名称的文件(/var/log/something.log).

它不处理任何信号以释放日志文件.我需要旋转该日志文件.

有没有办法在不更改应用程序且不丢失日志中的任何数据的情况下正确执行此操作?

解决方法

伊格纳西奥的回答引起了我的兴趣,所以我做了一些研究,并提出了下面的Perl脚本.如果您的服务将写入命名管道,它应该工作并可用于logrotate.

要使它工作,您需要将日志文件设置为命名管道.然后重命名现有文件

mkfifo /var/log/something.log

并编辑3个文件名以满足您的要求.运行您的服务,然后运行此守护程序,该守护程序应读取命名管道并将其写入新的日志文件.

如果你重命名/var/log/somethingrotateable.log然后将一个HUP发送到守护进程,它将自己生成并创建一个新的somethingrotateable.log来写入.如果使用logrotate一个postrotate脚本kill -HUP’cat /var/run/yourpidfile.pid’

#!/usr/bin/perl -w
use POSIX ();
use FindBin ();
use File::Basename ();
use File::Spec::Functions;
#
$|=1;
#
# Change the 3 filenames and paths below to meet your requirements.
#
my $FiFoFile = '/var/log/something.log';
my $LogFile = '/var/log/somethingrotateable.log';
my $PidFile = '/var/run/yourpidfile.pid';

# # make the daemon cross-platform,so exec always calls the script
# # itself with the right path,no matter how the script was invoked.
my $script = File::Basename::basename($0);
my $SELF = catfile $FindBin::Bin,$script;
#
# # POSIX unmasks the sigprocmask properly
my $sigset = POSIX::SigSet->new();
my $action = POSIX::SigAction->new('sigHUP_handler',$sigset,&POSIX::SA_NODEFER);
POSIX::sigaction(&POSIX::SIGHUP,$action);

sub sigHUP_handler {
#    print "Got SIGHUP";
    exec($SELF,@ARGV) or die "Couldn't restart: $!\n";
   }

#open the logfile to write to
open(LOGFILE,">>$LogFile") or die "Can't open $LogFile";
open(PIDFILE,">$PidFile") or die "Can't open PID File $PidFile";
print PIDFILE "$$\n";
close PIDFILE;
readLog();

sub readLog {
sysopen(FIFO,$FiFoFile,0)  or die "Can't open $FiFoFile";
while ( my $LogLine = <FIFO>) {
    print LOGFILE $LogLine;
   }
}

相关文章

文章浏览阅读1.8k次,点赞63次,收藏54次。Linux下的目录权限...
文章浏览阅读1.6k次,点赞44次,收藏38次。关于Qt的安装、Wi...
本文介绍了使用shell脚本编写一个 Hello
文章浏览阅读1.5k次,点赞37次,收藏43次。【Linux】初识Lin...
文章浏览阅读3k次,点赞34次,收藏156次。Linux超详细笔记,...
文章浏览阅读6.8k次,点赞109次,收藏114次。【Linux】 Open...