Retrieve logs for previous 4 hours

Hi,

I am in the process of configuring a script, and i intend it to retrieve logs for previous four hours, and then scan for predefined errors.

I am kind of stuck on the log retrieval part where the script will run early morning like 1 AM or 2 AM, the command as posted below will give me negative numbers, and may not give me previous day's date.

Log_From_Time=`date '+%d\/%b\/%Y:%H' | awk -F: '{printf("%s:%02d\n",$1,$2-4)}'`

P.S : The extra slash i put on date is on purpose, and i would like that way.

Please help me how to accomplish this.

Thanks, John.

If you are running on a linux based OS, man date (linux) supports relative times, as in:

trogdor $ date
Mon Jan 17 15:08:38 EST 2011
trogdor $ date -d '4 hours ago' '+%d/%b/%Y:%H'
17/Jan/2011:11

If your version of date does not support the "-d" option, you could select a timezone that is four hours before yours. For instance, I am in the "America/New York" timezone, so if I:

trogdor $  Log_From_Time=`TZ=America/Anchorage date '+%d/%b/%Y:%H'`
trogdor $ echo $Log_From_Time
17/Jan/2011:11

But it is frightening how non-portable that is.

If you have a C compiler available I've written a little C program that prints a time with secs adjustment (positive or negative) you can also specify the output format but it defaults to %d/%b/%Y:%H
dateadj.c

#include <time.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
   long long adj = 0;
   char res[1024], fmt[1024] = "%d/%b/%Y:%H";
   time_t secs_now;
   struct tm *time_now = (struct tm *)malloc(sizeof(struct tm));
   if (argc > 1) adj=atoll(argv[argc-1]);
   if (argc > 2) strcpy(fmt, argv[1]);
   if (argc > 1 && *argv[argc-1] == '@') secs_now=atoll(argv[argc-1]+1);
   else secs_now = time(NULL)+adj;
   *time_now = *localtime(&secs_now);
   strftime(res, 1024, fmt, time_now);
   free(time_now);
   puts(res);
   return 0;
}

Compile with cc -o dateadj dateadj.c , or replace cc with gcc if you have it.

Some usage examples:

$ ./dateadj   
18/Jan/2011:08
$ ./dateadj $((-3600 * 4))
18/Jan/2011:04
$ ./dateadj '%s' 0
1295302878
$ ./dateadj @1295302878
18/Jan/2011:08

Try this,

#!/usr/bin/perl
@abbr = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
($year,$month,$day,$hr)=(localtime(time-4 * 60 * 60))[5,4,3,2];
$year+=1900;
$month++;
print "$day\\/$abbr[$month]\\/$year:$hr\n";

Hi Ludwig,

Does the time difference between Anchorage and New York remains same across the year? or does it differ?

My servers are located in ET. So i could use the suggested steps.

Thanks.