Created
March 26, 2013 14:48
-
-
Save ahill00/5245922 to your computer and use it in GitHub Desktop.
Useful if you want your logfiles to have YYYYMMDD in them but they've already been logrotated.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
""" | |
Simple script to datestamp log files that haven't been stamped via logrotate. | |
""" | |
import datetime | |
import os | |
import re | |
import sys | |
try: | |
log_path = sys.argv[1] | |
except IndexError: | |
print "USAGE: prerotate.py <path>" | |
quit() | |
extension = ".gz" | |
files = os.listdir(log_path) | |
for obj in files: | |
if obj.endswith(extension): | |
pattern = ".*[0-9]{4}[0-9]{2}[0-9]{2}\%s$" % extension | |
reg = re.compile(pattern) | |
if not reg.match(obj): | |
(mode, ino, dev, nlink, uid, gid, size, atime, | |
mtime, ctime) = os.stat(log_path + obj) | |
datestamp = datetime.datetime.fromtimestamp( | |
int(mtime)).strftime('%Y%m%d') | |
fileparts = obj.split(".") | |
parts_count = len(fileparts) | |
filename = fileparts[0] | |
first_extension = fileparts[1] | |
if parts_count == 3: | |
new_name = filename + '-' + datestamp + extension | |
elif parts_count == 4: | |
new_name = filename + '.' + \ | |
first_extension + '-' + datestamp + extension | |
print "Renaming %s to %s" % (log_path + obj, log_path + new_name) | |
os.rename(log_path + obj, log_path + new_name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment