1212// See the License for the specific language governing permissions and
1313// limitations under the License.
1414
15+ //go:build !windows
1516// +build !windows
1617
1718// Package journal provides write bindings to the local systemd journal.
5354 onceConn sync.Once
5455)
5556
56- func init () {
57- onceConn .Do (initConn )
58- }
59-
6057// Enabled checks whether the local systemd journal is available for logging.
6158func Enabled () bool {
62- onceConn .Do (initConn )
63-
64- if (* net .UnixConn )(atomic .LoadPointer (& unixConnPtr )) == nil {
59+ if c := getOrInitConn (); c == nil {
6560 return false
6661 }
6762
@@ -82,7 +77,7 @@ func Enabled() bool {
8277// (http://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html)
8378// for more details. vars may be nil.
8479func Send (message string , priority Priority , vars map [string ]string ) error {
85- conn := ( * net . UnixConn )( atomic . LoadPointer ( & unixConnPtr ) )
80+ conn := getOrInitConn ( )
8681 if conn == nil {
8782 return errors .New ("could not initialize socket to journald" )
8883 }
@@ -126,6 +121,16 @@ func Send(message string, priority Priority, vars map[string]string) error {
126121 return nil
127122}
128123
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+
129134func appendVariable (w io.Writer , name , value string ) {
130135 if err := validVarName (name ); err != nil {
131136 fmt .Fprintf (os .Stderr , "variable name %s contains invalid character, ignoring\n " , name )
@@ -194,7 +199,7 @@ func tempFd() (*os.File, error) {
194199}
195200
196201// 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 .
198203func initConn () {
199204 autobind , err := net .ResolveUnixAddr ("unixgram" , "" )
200205 if err != nil {
0 commit comments