Skip to content

Instantly share code, notes, and snippets.

@jpalala
Last active August 29, 2015 14:07
Show Gist options
  • Save jpalala/b75065f657fb029bba37 to your computer and use it in GitHub Desktop.
Save jpalala/b75065f657fb029bba37 to your computer and use it in GitHub Desktop.
find out how many hits from a nginx log or apache log by writing a summarized log file
#!/usr/bin/python
from time import mktime, gmtime, strftime, time
import datetime
log = '/var/log/nginx/logs/access_log'
num_lines = 0
num_words = 0
with open(log, 'r') as f:
for line in f:
words = line.split()
num_lines += 1
num_words += len(words)
# generate time and other things for writing a log file
log_time = strftime("%Y-%m-%d %H:%M:%S", gmtime())
timestamp_for_logfile = strftime("%Y%m%d%H%M%S", gmtime())
log_filename = 'www.site-example.com-' + timestamp_for_logfile + '.log'
content = 'Log has ' + str(num_lines) + ' hits and over ' + str(num_words) + ' words.' + \
'\r\n Log Generated: '+ log_time
# write to file
log_file = "/var/log/%s" % log_filename
# correct way to write to files - http://docs.python.org/reference/compound_stmts.html#the-with-statement
# http://docs.python.org/library/functions.html?highlight=open#open
with open( log_file, 'w' ) as file:
file.write(content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment