2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2019 Sergey Matveev <stargrave@stargrave.org>
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, version 3 of the License.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
27 "golang.org/x/sys/unix"
32 type SDS map[string]interface{}
34 func sdFmt(who string, sds SDS) string {
35 keys := make([]string, 0, len(sds))
36 for k, _ := range sds {
37 keys = append(keys, k)
40 result := make([]string, 0, 1+len(keys))
41 result = append(result, "["+who)
42 for _, k := range keys {
43 result = append(result, fmt.Sprintf(`%s="%s"`, k, sds[k]))
45 return strings.Join(result, " ") + "]"
48 func msgFmt(level LogLevel, who string, sds SDS, msg string) string {
49 result := fmt.Sprintf(
52 time.Now().UTC().Format(time.RFC3339Nano),
61 func (ctx *Ctx) Log(msg string) {
62 fdLock, err := os.OpenFile(
64 os.O_CREATE|os.O_WRONLY,
68 fmt.Fprintln(os.Stderr, "Can not open lock for log:", err)
71 fdLockFd := int(fdLock.Fd())
72 err = unix.Flock(fdLockFd, unix.LOCK_EX)
74 fmt.Fprintln(os.Stderr, "Can not acquire lock for log:", err)
77 defer unix.Flock(fdLockFd, unix.LOCK_UN)
78 fd, err := os.OpenFile(
80 os.O_CREATE|os.O_WRONLY|os.O_APPEND,
84 fmt.Fprintln(os.Stderr, "Can not open log:", err)
91 func (ctx *Ctx) LogD(who string, sds SDS, msg string) {
95 fmt.Fprint(os.Stderr, msgFmt(LogLevel("D"), who, sds, msg))
98 func (ctx *Ctx) LogI(who string, sds SDS, msg string) {
99 msg = msgFmt(LogLevel("I"), who, sds, msg)
101 fmt.Fprintln(os.Stderr, ctx.Humanize(msg))
106 func (ctx *Ctx) LogP(who string, sds SDS, msg string) {
108 fmt.Fprintln(os.Stderr, ctx.Humanize(msgFmt(LogLevel("P"), who, sds, msg)))
112 func (ctx *Ctx) LogE(who string, sds SDS, msg string) {
113 msg = msgFmt(LogLevel("E"), who, sds, msg)
117 fmt.Fprintln(os.Stderr, ctx.Humanize(msg))
121 func SdsAdd(sds, add SDS) SDS {
123 for k, v := range sds {
126 for k, v := range add {