Skip to content

Commit 8fb7428

Browse files
author
David Noble
committed
Improved error handling
Signed-off-by: David Noble <[email protected]>
1 parent 4348a99 commit 8fb7428

File tree

5 files changed

+66
-69
lines changed

5 files changed

+66
-69
lines changed

examples/searchcommands_app/default/logging.conf

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,25 +13,34 @@ handlers = stderr ; Default: stderr
1313
[logger_CountMatchesCommand]
1414
qualname = CountMatchesCommand
1515
level = NOTSET ; Default: WARNING
16-
handlers = stderr ; Default: stderr
16+
handlers = file ; Default: stderr
1717
propagate = 0 ; Default: 1
1818

1919
[logger_SimulateCommand]
2020
qualname = SimulateCommand
2121
level = NOTSET ; Default: WARNING
22-
handlers = stderr ; Default: stderr
22+
handlers = file ; Default: stderr
2323
propagate = 0 ; Default: 1
2424

2525
[logger_SumCommand]
2626
qualname = SumCommand
2727
level = NOTSET ; Default: WARNING
28-
handlers = stderr ; Default: stderr
28+
handlers = file ; Default: stderr
2929
propagate = 0 ; Default: 1
3030

3131
[handlers]
32-
keys=stderr
32+
# See [logging.handlers](http://goo.gl/9aoOx)
33+
keys=file, stderr
34+
35+
[handler_file]
36+
# Select this handler to log events to $SPLUNK_HOME/etc/apps/searchcommands_app/searchcommands_app.log
37+
class = logging.FileHandler
38+
level = NOTSET
39+
args = ('searchcommand_app.log', 'a', 'utf-8', True)
40+
formatter = search_command
3341

3442
[handler_stderr]
43+
# Select this handler to log events to $SPLUNK_HOME/var/log/splunk/splunkd.log
3544
class = logging.StreamHandler
3645
level = NOTSET
3746
args = (sys.stderr,)

splunklib/searchcommands/generating_command.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -76,12 +76,9 @@ def generate(self):
7676
raise NotImplementedError('GeneratingCommand.generate(self)')
7777

7878
def _execute(self, operation, reader, writer):
79-
try:
80-
for record in operation():
81-
writer.writerow(record)
82-
except Exception as e:
83-
from traceback import format_exc
84-
self._exit(format_exc(), e, 1)
79+
for record in operation():
80+
writer.writerow(record)
81+
return
8582

8683
def _prepare(self, argv, input_file):
8784
ConfigurationSettings = type(self).ConfigurationSettings

splunklib/searchcommands/reporting_command.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -72,12 +72,9 @@ def reduce(self, records):
7272
raise NotImplementedError('reduce(self, records)')
7373

7474
def _execute(self, operation, reader, writer):
75-
try:
76-
for record in operation(SearchCommand.records(reader)):
77-
writer.writerow(record)
78-
except Exception as e:
79-
from traceback import format_exc
80-
self._exit(format_exc(), e, 1)
75+
for record in operation(SearchCommand.records(reader)):
76+
writer.writerow(record)
77+
return
8178

8279
def _prepare(self, argv, input_file):
8380
if len(argv) >= 3 and argv[2] == '__map__':

splunklib/searchcommands/search_command.py

Lines changed: 45 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,6 @@ def __init__(self):
5959
self._configuration = None
6060
self._fieldnames = None
6161
self._option_view = None
62-
self._output_file = None
6362
self._search_results_info = None
6463
self._service = None
6564

@@ -282,61 +281,66 @@ def process(self, args=argv, input_file=stdin, output_file=stdout):
282281
283282
"""
284283
self.logger.debug('%s arguments: %s' % (type(self).__name__, args))
285-
self._outputfile = output_file
286284
self._configuration = None
287285

288-
if len(args) >= 2 and args[1] == '__GETINFO__':
286+
try:
287+
if len(args) >= 2 and args[1] == '__GETINFO__':
288+
289+
ConfigurationSettings, operation, args, reader = self._prepare(
290+
args, input_file=None)
289291

290-
ConfigurationSettings, operation, args, reader = self._prepare(
291-
args, input_file=None)
292-
try:
293292
self.parser.parse(args, self)
294-
except (SyntaxError, ValueError) as e:
295-
from traceback import format_exc
296-
self._exit(format_exc(), e, 1)
297293

298-
self._configuration = ConfigurationSettings(self)
294+
self._configuration = ConfigurationSettings(self)
299295

300-
writer = csv.DictWriter(
301-
output_file, self, self.configuration.keys(), mv_delimiter=',')
302-
writer.writerow(self.configuration.items())
296+
writer = csv.DictWriter(
297+
output_file, self, self.configuration.keys(), mv_delimiter=',')
298+
writer.writerow(self.configuration.items())
303299

304-
elif len(args) >= 2 and args[1] == '__EXECUTE__':
300+
elif len(args) >= 2 and args[1] == '__EXECUTE__':
305301

306-
self.input_header.read(input_file)
307-
ConfigurationSettings, operation, args, reader = self._prepare(
308-
args, input_file)
302+
self.input_header.read(input_file)
303+
304+
ConfigurationSettings, operation, args, reader = self._prepare(
305+
args, input_file)
309306

310-
try:
311307
self.parser.parse(args, self)
312-
except (SyntaxError, ValueError) as e:
313-
from traceback import format_exc
314-
self._exit(format_exc(), e, 1)
315308

316-
self._configuration = ConfigurationSettings(self)
309+
self._configuration = ConfigurationSettings(self)
317310

318-
if self.show_configuration:
319-
self.messages.append(
320-
'info_message', '%s command configuration settings: %s'
321-
% (self.name, self._configuration))
311+
if self.show_configuration:
312+
self.messages.append(
313+
'info_message', '%s command configuration settings: %s'
314+
% (self.name, self._configuration))
322315

323-
writer = csv.DictWriter(output_file, self)
324-
self._execute(operation, reader, writer)
316+
writer = csv.DictWriter(output_file, self)
317+
self._execute(operation, reader, writer)
325318

326-
else:
319+
else:
327320

328-
file_name = path.basename(args[0])
329-
message = (
330-
'Command {0} appears to be statically configured and static '
331-
'configuration is unsupported by splunklib.searchcommands. '
332-
'Please ensure that default/commands.conf contains this '
333-
'stanza: '
334-
'[{0}] | '
335-
'filename = {1} | '
336-
'supports_getinfo = true | '
337-
'supports_rawargs = true | '
338-
'outputheader = true'.format(type(self).name, file_name))
339-
self._exit(message, message, 1)
321+
file_name = path.basename(args[0])
322+
message = (
323+
'Command {0} appears to be statically configured and static '
324+
'configuration is unsupported by splunklib.searchcommands. '
325+
'Please ensure that default/commands.conf contains this '
326+
'stanza: '
327+
'[{0}] | '
328+
'filename = {1} | '
329+
'supports_getinfo = true | '
330+
'supports_rawargs = true | '
331+
'outputheader = true'.format(type(self).name, file_name))
332+
raise NotImplementedError(message)
333+
334+
except Exception as error:
335+
336+
from traceback import format_exc
337+
338+
writer = csv.DictWriter(output_file, self, fieldnames=['ERROR'])
339+
writer.writerow({'ERROR': error})
340+
self.logger.error(format_exc())
341+
exit(1)
342+
343+
return
340344

341345
@staticmethod
342346
def records(reader):
@@ -350,12 +354,6 @@ def _prepare(self, argv, input_file):
350354
def _execute(self, operation, reader, writer):
351355
raise NotImplementedError('SearchCommand._configure(self, argv)')
352356

353-
def _exit(self, log, error, status_code):
354-
writer = csv.DictWriter(self.output_file, self, fieldnames=['ERROR'])
355-
writer.writerow({'ERROR': error})
356-
self.logger.error(log)
357-
exit(status_code)
358-
359357
#endregion
360358

361359
#region Types

splunklib/searchcommands/streaming_command.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -71,12 +71,8 @@ def stream(self, records):
7171
raise NotImplementedError('StreamingCommand.stream(self, records)')
7272

7373
def _execute(self, operation, reader, writer):
74-
try:
75-
for record in operation(SearchCommand.records(reader)):
76-
writer.writerow(record)
77-
except Exception as e:
78-
from traceback import format_exc
79-
self._exit(format_exc(), e, 1)
74+
for record in operation(SearchCommand.records(reader)):
75+
writer.writerow(record)
8076

8177
def _prepare(self, argv, input_file):
8278
ConfigurationSettings = type(self).ConfigurationSettings

0 commit comments

Comments
 (0)