1+ package net .swofty .commons ;
2+
3+ import java .util .Collection ;
4+ import java .util .Collections ;
5+ import java .util .Map ;
6+
7+ import io .sentry .Sentry ;
8+ import io .sentry .SentryLogLevel ;
9+ import org .tinylog .Level ;
10+ import org .tinylog .core .ConfigurationParser ;
11+ import org .tinylog .core .LogEntry ;
12+ import org .tinylog .core .LogEntryValue ;
13+ import org .tinylog .provider .InternalLogger ;
14+ import org .tinylog .writers .AbstractFormatPatternWriter ;
15+
16+
17+ public final class SentryWriter extends AbstractFormatPatternWriter {
18+
19+ private final Level errorLevel ;
20+
21+ public SentryWriter () {
22+ this (Collections .<String , String >emptyMap ());
23+ }
24+
25+ /**
26+ * @param properties
27+ * Configuration for writer
28+ */
29+ public SentryWriter (final Map <String , String > properties ) {
30+ super (properties );
31+
32+ // Set the default level for stderr logging
33+ Level levelStream = Level .WARN ;
34+
35+ // Check stream property
36+ String stream = getStringValue ("stream" );
37+ if (stream != null ) {
38+ // Check whether we have the err@LEVEL syntax
39+ String [] streams = stream .split ("@" , 2 );
40+ if (streams .length == 2 ) {
41+ levelStream = ConfigurationParser .parse (streams [1 ], levelStream );
42+ if (!streams [0 ].equals ("err" )) {
43+ InternalLogger .log (Level .ERROR , "Stream with level must be \" err\" , \" " + streams [0 ] + "\" is an invalid name" );
44+ }
45+ stream = null ;
46+ }
47+ }
48+
49+ if (stream == null ) {
50+ errorLevel = levelStream ;
51+ } else if ("err" .equalsIgnoreCase (stream )) {
52+ errorLevel = Level .TRACE ;
53+ } else if ("out" .equalsIgnoreCase (stream )) {
54+ errorLevel = Level .OFF ;
55+ } else {
56+ InternalLogger .log (Level .ERROR , "Stream must be \" out\" or \" err\" , \" " + stream + "\" is an invalid stream name" );
57+ errorLevel = levelStream ;
58+ }
59+ }
60+
61+ @ Override
62+ public Collection <LogEntryValue > getRequiredLogEntryValues () {
63+ Collection <LogEntryValue > logEntryValues = super .getRequiredLogEntryValues ();
64+ logEntryValues .add (LogEntryValue .LEVEL );
65+ return logEntryValues ;
66+ }
67+
68+ @ Override
69+ public void write (final LogEntry logEntry ) {
70+ SentryLogLevel sentryLevel ;
71+ try {
72+ sentryLevel = SentryLogLevel .valueOf (logEntry .getLevel ().name ());
73+ } catch (IllegalArgumentException e ) {
74+ sentryLevel = SentryLogLevel .INFO ;
75+ }
76+
77+ Sentry .logger ().log (sentryLevel , render (logEntry ));
78+ if (logEntry .getLevel ().ordinal () < errorLevel .ordinal ()) {
79+ System .out .print (render (logEntry ));
80+ } else {
81+ System .err .print (render (logEntry ));
82+ }
83+ }
84+
85+ @ Override
86+ public void flush () {
87+ }
88+
89+ @ Override
90+ public void close () {
91+ }
92+
93+ }
0 commit comments