12
12
// See the License for the specific language governing permissions and
13
13
// limitations under the License.
14
14
15
+ //go:build !windows
15
16
// +build !windows
16
17
17
18
// Package journal provides write bindings to the local systemd journal.
53
54
onceConn sync.Once
54
55
)
55
56
56
- func init () {
57
- onceConn .Do (initConn )
58
- }
59
-
60
57
// Enabled checks whether the local systemd journal is available for logging.
61
58
func Enabled () bool {
62
- onceConn .Do (initConn )
63
-
64
- if (* net .UnixConn )(atomic .LoadPointer (& unixConnPtr )) == nil {
59
+ if c := getOrInitConn (); c == nil {
65
60
return false
66
61
}
67
62
@@ -82,7 +77,7 @@ func Enabled() bool {
82
77
// (http://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html)
83
78
// for more details. vars may be nil.
84
79
func Send (message string , priority Priority , vars map [string ]string ) error {
85
- conn := ( * net . UnixConn )( atomic . LoadPointer ( & unixConnPtr ) )
80
+ conn := getOrInitConn ( )
86
81
if conn == nil {
87
82
return errors .New ("could not initialize socket to journald" )
88
83
}
@@ -126,6 +121,16 @@ func Send(message string, priority Priority, vars map[string]string) error {
126
121
return nil
127
122
}
128
123
124
+ // getOrInitConn attempts to get the global `unixConnPtr` socket, initializing if necessary
125
+ func getOrInitConn () * net.UnixConn {
126
+ conn := (* net .UnixConn )(atomic .LoadPointer (& unixConnPtr ))
127
+ if conn != nil {
128
+ return conn
129
+ }
130
+ onceConn .Do (initConn )
131
+ return (* net .UnixConn )(atomic .LoadPointer (& unixConnPtr ))
132
+ }
133
+
129
134
func appendVariable (w io.Writer , name , value string ) {
130
135
if err := validVarName (name ); err != nil {
131
136
fmt .Fprintf (os .Stderr , "variable name %s contains invalid character, ignoring\n " , name )
@@ -194,7 +199,7 @@ func tempFd() (*os.File, error) {
194
199
}
195
200
196
201
// initConn initializes the global `unixConnPtr` socket.
197
- // It is meant to be called exactly once, at program startup .
202
+ // It is automatically called when needed .
198
203
func initConn () {
199
204
autobind , err := net .ResolveUnixAddr ("unixgram" , "" )
200
205
if err != nil {
0 commit comments