1+ # Copyright 2011-2013 Splunk, Inc.
2+ #
3+ # Licensed under the Apache License, Version 2.0 (the "License"): you may
4+ # not use this file except in compliance with the License. You may obtain
5+ # a copy of the License at
6+ #
7+ # http://www.apache.org/licenses/LICENSE-2.0
8+ #
9+ # Unless required by applicable law or agreed to in writing, software
10+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12+ # License for the specific language governing permissions and limitations
13+ # under the License.
14+
15+ from splunklib .modularinput .event import Event , ET , StringIO
16+ import sys
17+
18+ class EventWriter (object ):
19+ """EventWriter writes events and error messages to Splunk from a modular input."""
20+ def __init__ (self , output = sys .stdout , error = sys .stderr ):
21+ """
22+ :param output: where to write the output, defaults to sys.stdout
23+ :param error:
24+ """
25+ # The severities that Splunk understands for log messages from modular inputs.
26+ self .DEBUG = "DEBUG"
27+ self .INFO = "INFO"
28+ self .WARN = "WARN"
29+ self .ERROR = "ERROR"
30+ self .FATAL = "FATAL"
31+
32+ self .output_writer = output
33+ self .error_writer = error
34+
35+ self .header_written = False
36+
37+ def write_event (self , event ):
38+ """Write an Event object to Splunk.
39+
40+ :param event: an Event object
41+ """
42+
43+ if not self .header_written :
44+ self .output_writer .write ("<stream>" )
45+ self .header_written = True
46+ #try:
47+ event .write_to (self .output_writer )
48+ #except ValueError as ve:
49+ #self.log(self.WARN, ve.message)
50+
51+ def log (self , severity , message ):
52+ """Log messages about the state of this modular input to Splunk. These messages will show up in Splunk's
53+ internal logs
54+
55+ :param severity: string, severity of message, see severites in __init__
56+ :param message: message to log
57+ """
58+
59+ self .error_writer .write ("%s %s\n " % (severity , message ))
60+ self .error_writer .flush ()
61+
62+ def write_xml_document (self , document ):
63+ """Write an ElementTree to the output stream
64+
65+ :param document: an ElementTree object
66+ """
67+ stream = StringIO .StringIO ()
68+ stream .write (ET .tostring (document , "us-ascii" , "xml" ))
69+ stream .flush ()
70+ self .output_writer .write (stream .getvalue ())
71+ self .output_writer .flush ()
72+
73+ def close (self ):
74+ """Write the closing </stream> tag to make this XML well formed."""
75+ self .output_writer .write ("</stream>" )
0 commit comments