-
Notifications
You must be signed in to change notification settings - Fork 1
/
plex-log-saver.py
174 lines (130 loc) · 5.66 KB
/
plex-log-saver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- python -*-
from __future__ import print_function
__license__ = """
The MIT License (MIT)
Copyright (c) 2013 Jacob Smith <kloptops@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import os
## Uncomment the next line if you plan on using this script in the windows
## task scheduler
#os.chdir(os.path.dirname(os.path.abspath(__file__)))
import json
import logging
from glob import glob as file_glob
# Only import what is needed, don't need or want requests.
from plex.util import BasketOfHandles, config_load, config_save, datetime_diff
from plex.lockfile import LockFile
from plex.parser import PlexLogParser
class PlexSuperLogParser(PlexLogParser):
def __init__(self, last_datetime, *args, **kwargs):
super(PlexSuperLogParser, self).__init__(**kwargs)
self.last_datetime = last_datetime
def line_body_filter(self, line_body):
# We don't want old records
if line_body['datetime'] <= self.last_datetime:
return False
# We don't want the useless lines following request lines.
if 'content' in line_body and line_body['content'].startswith(' *'):
return False
return super(PlexSuperLogParser, self).line_body_filter(line_body)
def main():
logging.info('{0:#^40}'.format('[ Plex Log Saver ]'))
if not os.path.isdir('logs'):
os.mkdir('logs')
config_file = os.path.join('logs', 'config.cfg')
config = config_load(config_file)
if config['plex_log_dir'] == '':
logging.info('Config missing "plex_log_dir", Exiting!')
print('Config missing "plex_log_dir", Exiting!')
return
log_file_template = os.path.join(
'logs', config['log_file_name'])
if config['log_save_mode'] == 'gzip':
import gzip
log_open = gzip.open
else:
log_open = open
last_datetime = tuple(map(int, config['plex_last_datetime'].split('-')))
log_parser = PlexSuperLogParser(last_datetime)
all_lines = []
# We're only interested in 'Plex Media Server.log' log files
# I've been able to so far get all of the info i need from those logs
log_file_glob = os.path.join(
config['plex_log_dir'], 'Plex Media Server.log*')
for log_file in file_glob(log_file_glob):
all_lines.extend(log_parser.parse_file(log_file))
if len(all_lines) == 0:
logging.info('No new lines, finishing.')
return
# Sort the logs based on datetime
all_lines.sort(key=lambda line_body: line_body['datetime'])
time_diff = datetime_diff(all_lines[0]['datetime'], last_datetime)
logging.info((
' Last entry last run:'
' {0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}').format(
*last_datetime))
logging.info((
'Earliest entry this run:'
' {0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}').format(
*all_lines[0]['datetime']))
if time_diff > 60:
logging.warn((
'Possibly missing {0} seconds of log files').format(time_diff))
logging.info('{0} new log lines added'.format(len(all_lines)))
## TODO: replace this! No longer needed...
# BasketOfHandles handles our open files for us,
# keeping only 5 open at a time.
with BasketOfHandles(log_open, 5) as basket:
for line_body in all_lines:
log_file_name = log_file_template.format(**line_body)
file_handle = basket.open(log_file_name, 'at')
json.dump(line_body, file_handle, sort_keys=True)
file_handle.write('\n')
if line_body['datetime'] > last_datetime:
last_datetime = line_body['datetime']
config['plex_last_datetime'] = '-'.join(map(str, last_datetime))
config_save(config_file, config)
logging.info('Finished.')
if __name__ == '__main__':
import gc
import time
with open('plex-log-saver.log', 'a') as file_handle:
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
stream=file_handle,
level=logging.DEBUG)
try:
while True:
# testing how much memory is used if it runs as a simple daemon
if os.path.isfile('__shutdown__'):
os.remove('__shutdown__')
break
with LockFile() as lock_file:
main()
gc.collect()
file_handle.flush()
finish_sleeping = time.time() + 60
while time.time() < finish_sleeping:
if os.path.isfile('__shutdown__'):
break
time.sleep(1)
except Exception as err:
logging.exception(err)
raise