Skip to content

Commit 75f33b0

Browse files
committed
journal: remove implicit initialization
some application could log to journald conditionally, the implicit initialization will always create a socket on init. We now create the socket only if necessary Signed-off-by: Nicola Murino <[email protected]>
1 parent 9ed442a commit 75f33b0

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed

journal/journal_unix.go

+14-9
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
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.
@@ -53,15 +54,9 @@ var (
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.
6158
func 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.
8479
func 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+
129134
func 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.
198203
func initConn() {
199204
autobind, err := net.ResolveUnixAddr("unixgram", "")
200205
if err != nil {

0 commit comments

Comments
 (0)