...

Package log

import "github.com/Diarkis/diarkis/log"
Overview
Index
Subdirectories

Overview ▾

Package log ▷

Log

Diarkis logger.

Log Configurations

Log configurations are explained below.

{
  "level": "verbose",
  "levels": {
    "$(logger_name)": "verbose",
  },
  "timeZone": "local",
  "color": true,
  "flat": false,
  "filePath": "path/to/log/file"
}

Configuration Values

level - Default is "verbose"

levels - You may configure log level per logger name.

Controls logger level: verbose < network < sys < debug(trace) < info < notice < warn < error < fatal.

+----------------+----------------------------------------------------------------------------------------------------+---------+
| Log Level Name | Description                                                                                        |         |
+----------------+----------------------------------------------------------------------------------------------------+---------+
| verbose        | Lowest logging level to see what is taking place under the hood. Must never be used in production. | Default |
| network        | Lower than sys log level to output UDP/TCP network related logs.                                   |         |
| sys            | Second lowest logging level to log more detailed information.                                      |         |
| debug          | Logging debug purpose information usually expected to be used in application level of the code.    |         |
| info           | Logging starting and shutting down log as well as other must see information.                      |         |
| notice         | Should be used to log information that is important for the application, but not as critical.      |         |
| warn           | Warning information that is not errors, but should be logged and reviewed later.                   |         |
| error          | Errors that may be caused by either the user or the application.                                   |         |
| fatal          | Logging of unrecoverable problems.                                                                 |         |
+----------------+----------------------------------------------------------------------------------------------------+---------+

We suggest using log level info for production.

timeZone - Default is "utc"

Valid configuration value are "utc" or "local". Default is UTC.

+----------------+-----------------+---------+
| Time Zone Name | Description     |         |
+----------------+-----------------+---------+
| utc            | UTC Time zone   | Default |
| local          | Local time zone |         |
+----------------+-----------------+---------+

We suggest using UTC time zone for multiple cluster environment.

color - Default is true

If false, the output log has no color. The default is true.

flat - Default is false

If set to true, logging data will not contain line breaks. This configuration is recommended to be paired to env DIARKIS_JSON_LOG=true.

filePath - Default is ""

File path to output log data to (absolute path).

The absolute file path to write the logging data to. This configuration should be used if you need to leave log files somewhere on disk. Leave this empty to disable it.

Environment Variable Used By Log Module

DIARKIS_JSON_LOG=true

This converts all output log into JSON.

Change Log Level For A Specific Logger Name at Runtime

Diarkis logger allows you to change a specific logger's log level in runtime as well.

Logger name is the string output that is wrapped in < and >. If you see <SERVER>, then logger name is SERVER.

Below is the step by step operation to change log level by logger name in runtime.

1. Create a signal command file named DIARKIS_SIGUSR1 under /tmp/ directory. It should look like this: /tmp/DIARKIS_SIGUSR1

▶︎ Enable runtime log level change by logger name

DIARKIS_SIGUSR1 file must contain the following to enable runtime log level change:

LogLevelChangeByName
Enable
$(logger_name)
$(log_level)

Example:

The example below will enable verbose level of logging just for "ROOM" logs.

LogLevelChangeByName
Enable
ROOM
Verbose

▶︎ Disable runtime log level change by logger name

DIARKIS_SIGUSR1 file must contain the following to disable runtime log level change:

LogLevelChangeByName
Disable

Change Log Level Globally At Runtime

You may change log level for all logging at runtime.

[IMPORTANT] If LogLevelChangeByName is enabled, it takes the highest priority for the specified log name.

▶︎ TaskName: LogLevel:Verbose

This operation will change Diarkis logger's log level at runtime to verbose.

▶︎ TaskName: LogLevel:Network

This operation will change Diarkis logger's log level at runtime to network.

▶︎ TaskName: LogLevel:Sys

This operation will change Diarkis logger's log level at runtime to sys.

▶︎ TaskName: LogLevel:Debug

This operation will change Diarkis logger's log level at runtime to debug.

▶︎ TaskName: LogLevel:Info

This operation will change Diarkis logger's log level at runtime to info.

▶︎ TaskName: LogLevel:Error

This operation will change Diarkis logger's log level at runtime to error.

▶︎ TaskName: LogLevel:Fatal

This operation will change Diarkis logger's log level at runtime to fatal.

Rotate Log Level Globally

▶︎ TaskName: LogLevelChange

This operation will change Diarkis logger's log level at runtime. Every time this operation is called the log level changes.

[IMPORTANT] If LogLevelChangeByName is enabled, it takes the highest priority for the specified log name.

Below is the order of log level change:

   ╭─────────╮ ╭─────────╮ ╭─────────╮ ╭─────────╮ ╭─────────╮
╔═▶︎│ Verbose │▶︎│ Network │▶︎│   Sys   │▶︎│  Debug  │▶︎│   Info  │══╗
║  ╰─────────╯ ╰─────────╯ ╰─────────╯ ╰─────────╯ ╰─────────╯  ║
╚═══════════════════════════════════════════════════════════════╝

Formatted Logging

Log module lets you format logging outputs and it supports JSON format as well.

Formatted Text Logging Example:

logger.Debugf("Debugging logging", "RoomID", roomID, "Object pointer address", obj)
// Output:
// Debug logging	RoomID=[Value="19324322303022354543345" Type=string Pointer=NA]	Object=[Value={"Name":"Example Object","Value":1203} Type=*Object Pointer=0x005a134]

Formatted JSON Logging Example:

logger.Debugf("Debugging logging", "RoomID", roomID, "Object", obj)
// JSON Output:
// {
//   "logName":"Test",
//   "severity":"100",
//   "resource": {
//       "type":"Server",
//       "labels": {
//         "Message":"Debug logging",
//         "RoomID":{ "Value":"19324322303022354543345", "Type":"string","Pointer":"NA"},
//         "Object":{
//           "Type":"*Object",
//           "Pointer":"0x005a134",
//           "Value": {
//             "Name":"Example Object",
//             "Value": 1203
//           },
//         }
//       }
//     },
//     "timestamp":"2019-10-12T07:20:50.52Z"
//   }
// }

Index ▾

func AddFormat(name string, cb func(v interface{}) interface{}) bool
func ChangeLogLevelByName(params []string)
func CloseFileOutput(next func(error))
func Fmt(vals ...interface{}) string
func FmtBlue(msg string) string
func FmtDBlue(msg string) string
func FmtGreen(msg string) string
func FmtGrey(msg string) string
func FmtLBlue(msg string) string
func FmtPurple(msg string) string
func FmtRed(msg string) string
func FmtRedBg(msg string) string
func FmtYellow(msg string) string
func IsDebug() bool
func IsError() bool
func IsFatal() bool
func IsInfo() bool
func IsNetwork() bool
func IsNotice() bool
func IsSys() bool
func IsVerbose() bool
func IsWarn() bool
func Level(_level int)
func SetCustomOutput(custom func(formatted bool, name string, prefix string, level string, vals []interface{}) string)
func SetDebugLevel()
func SetErrorLevel()
func SetFatalLevel()
func SetInfoLevel()
func SetNetworkLevel()
func SetNoticeLevel()
func SetPrefix(prefix string)
func SetSysLevel()
func SetVerboseLevel()
func SetWarnLevel()
func Setup(confpath string)
func UpdateConfigs(configs map[string]interface{})
func UseCustomOutput()
func UseJSONFormat()
func UseStackdriverLogging()
type Logger
    func New(name string) *Logger
    func (logger *Logger) Debug(vals ...interface{})
    func (logger *Logger) Debugf(vals ...interface{})
    func (logger *Logger) DisableCustom()
    func (logger *Logger) EnableCustom()
    func (logger *Logger) Error(vals ...interface{})
    func (logger *Logger) Errorf(vals ...interface{})
    func (logger *Logger) Fatal(vals ...interface{})
    func (logger *Logger) Fatalf(vals ...interface{})
    func (logger *Logger) FmtDebug(vals ...interface{}) string
    func (logger *Logger) FmtError(vals ...interface{}) string
    func (logger *Logger) FmtFatal(vals ...interface{}) string
    func (logger *Logger) FmtInfo(vals ...interface{}) string
    func (logger *Logger) FmtNetwork(vals ...interface{}) string
    func (logger *Logger) FmtNotice(vals ...interface{}) string
    func (logger *Logger) FmtSys(vals ...interface{}) string
    func (logger *Logger) FmtVerbose(vals ...interface{}) string
    func (logger *Logger) FmtWarn(vals ...interface{}) string
    func (logger *Logger) Info(vals ...interface{})
    func (logger *Logger) Infof(vals ...interface{})
    func (logger *Logger) Network(vals ...interface{})
    func (logger *Logger) Networkf(vals ...interface{})
    func (logger *Logger) Notice(vals ...interface{})
    func (logger *Logger) Noticef(vals ...interface{})
    func (logger *Logger) Sys(vals ...interface{})
    func (logger *Logger) Sysf(vals ...interface{})
    func (logger *Logger) Trace(vals ...interface{})
    func (logger *Logger) Verbose(vals ...interface{})
    func (logger *Logger) Verbosef(vals ...interface{})
    func (logger *Logger) Warn(vals ...interface{})
    func (logger *Logger) Warnf(vals ...interface{})
    func (logger *Logger) Write(vals ...interface{})

func AddFormat

func AddFormat(name string, cb func(v interface{}) interface{}) bool

AddFormat assigns a formatting function to the given name.

[CRITICALLY IMPORTANT] You must NOT read from a map directly in the callback because of possible concurrent map access panic.

When formatted logging is used (Verbosef, Networkf, Sysf, Debugf, Infof, Warnf, Errorf, Fatalf), with the given name, it will execute the assigned callback.

Example

The example below will output a specific user property safely (UserFlag is just an example, of course).

log.AddFormat("UserFlag", func(v interface{}) interface{} {

  // If the value is not *User, we ignore and do nothing
  if _, ok := v.(*User) {
    return v
  }

  // We make sure to lock the user to print
  ud := v.(*User)

  ud.RLock()
  defer ud.RUnlock()

  // Format the output as a string
  formatted := log.Fmt("Properties:", ud.Data["UserFlag"])
  return formatted

})

func ChangeLogLevelByName

func ChangeLogLevelByName(params []string)

ChangeLogLevelByName is automatically called when the server receives SIGUSR1 signal and when there is /tmp/DIARKIS_SIGUSR1.

This function acts as a toggle.

DIARKIS_SIGUSR1 File Format

The first line must be ChangeLogLevelByName and the rest will be parameters.

[NOTE] line breaks will be the delimiter.

How To Disable Runtime Log Level Change

params[0] = "disable"

How To Enable Runtime Log For Specific Log By Name

params[0] = "enable"
params[1] = "$(log_name)"  // e.i. MESH, SERVER etc.
params[2] = "$(log_level)" // e.i. verbose, network etc.

func CloseFileOutput

func CloseFileOutput(next func(error))

CloseFileOutput [INTERNAL USE ONLY] Closes the file descriptor of log data if used

func Fmt

func Fmt(vals ...interface{}) string

Fmt alias of fmt.Sprint

func FmtBlue

func FmtBlue(msg string) string

FmtBlue Colorize the given string

func FmtDBlue

func FmtDBlue(msg string) string

FmtDBlue Colorize the given string

func FmtGreen

func FmtGreen(msg string) string

FmtGreen Colorize the given string

func FmtGrey

func FmtGrey(msg string) string

FmtGrey Colorize the given string

func FmtLBlue

func FmtLBlue(msg string) string

FmtLBlue Colorize the given string

func FmtPurple

func FmtPurple(msg string) string

FmtPurple Colorize the given string

func FmtRed

func FmtRed(msg string) string

FmtRed Colorize the given string

func FmtRedBg

func FmtRedBg(msg string) string

FmtRedBg Colorize the given string

func FmtYellow

func FmtYellow(msg string) string

FmtYellow Colorize the given string

func IsDebug

func IsDebug() bool

IsDebug returns true if the log level is debug

func IsError

func IsError() bool

IsError returns true if the log level is error

func IsFatal

func IsFatal() bool

IsFatal returns true if the log level is fatal

func IsInfo

func IsInfo() bool

IsInfo returns true if the log level is info

func IsNetwork

func IsNetwork() bool

IsNetwork returns true if the log level is network

func IsNotice

func IsNotice() bool

IsNotice returns true if the log level is notice

func IsSys

func IsSys() bool

IsSys returns true if the log level is sys

func IsVerbose

func IsVerbose() bool

IsVerbose returns true if the log level is verbose

func IsWarn

func IsWarn() bool

IsWarn returns true if the log level is warn

func Level

func Level(_level int)

Level Sets logging level

func SetCustomOutput

func SetCustomOutput(custom func(formatted bool, name string, prefix string, level string, vals []interface{}) string)

SetCustomOutput Registers a custom function to create a log output string

func SetDebugLevel

func SetDebugLevel()

SetDebugLevel set log level to debug

func SetErrorLevel

func SetErrorLevel()

SetErrorLevel set log level to error

func SetFatalLevel

func SetFatalLevel()

SetFatalLevel set log level to fatal

func SetInfoLevel

func SetInfoLevel()

SetInfoLevel set log level to info

func SetNetworkLevel

func SetNetworkLevel()

SetNetworkLevel set log level to sys

func SetNoticeLevel

func SetNoticeLevel()

SetNoticeLevel set log level to notice

func SetPrefix

func SetPrefix(prefix string)

SetPrefix Sets a prefix for every log

func SetSysLevel

func SetSysLevel()

SetSysLevel set log level to sys

func SetVerboseLevel

func SetVerboseLevel()

SetVerboseLevel set log level to verbose

func SetWarnLevel

func SetWarnLevel()

SetWarnLevel set log level to warn

func Setup

func Setup(confpath string)

Setup Load a configuration file into memory - pass an empty string to load nothing

func UpdateConfigs

func UpdateConfigs(configs map[string]interface{})

UpdateConfigs Apply configurations It can be executed in runtime to update the configurations also

func UseCustomOutput

func UseCustomOutput()

UseCustomOutput Enables custom output for all log data.

func UseJSONFormat

func UseJSONFormat()

UseJSONFormat formats the log with JSON format.

func UseStackdriverLogging

func UseStackdriverLogging()

UseStackdriverLogging is an alias of UseJSONFormat

type Logger

Logger Logger data structure

type Logger struct {
    Name string
    // contains filtered or unexported fields
}

func New

func New(name string) *Logger

New Creates a new logger

func (*Logger) Debug

func (logger *Logger) Debug(vals ...interface{})

Debug Outputs a log to stdout stream

func (*Logger) Debugf

func (logger *Logger) Debugf(vals ...interface{})

Debugf outputs formmated logging.

This is useful when you need to format the logging message.

[IMPORTANT] FormattedText supports JSON format log output as well.

Example:

logger.Debugf("This is a log", "intVar", 123, "stringVar", "aaa", "object", obj)

func (*Logger) DisableCustom

func (logger *Logger) DisableCustom()

DisableCustom blocks logger.Write()

func (*Logger) EnableCustom

func (logger *Logger) EnableCustom()

EnableCustom allows logger.Write()

func (*Logger) Error

func (logger *Logger) Error(vals ...interface{})

Error Outputs a log to stdout stream

func (*Logger) Errorf

func (logger *Logger) Errorf(vals ...interface{})

Errorf outputs formmated logging.

This is useful when you need to format the logging message.

[IMPORTANT] FormattedText supports JSON format log output as well.

Example:

logger.Errorf("This is a log", "intVar", 123, "stringVar", "aaa", "object", obj)

func (*Logger) Fatal

func (logger *Logger) Fatal(vals ...interface{})

Fatal Outputs a log to stdout stream

func (*Logger) Fatalf

func (logger *Logger) Fatalf(vals ...interface{})

Fatalf outputs formmated logging.

This is useful when you need to format the logging message.

[IMPORTANT] FormattedText supports JSON format log output as well.

Example:

logger.Fatalf("This is a log", "intVar", 123, "stringVar", "aaa", "object", obj)

func (*Logger) FmtDebug

func (logger *Logger) FmtDebug(vals ...interface{}) string

FmtDebug Formats given strings and returns it for logging purpose

func (*Logger) FmtError

func (logger *Logger) FmtError(vals ...interface{}) string

FmtError Formats given strings and returns it for logging purpose

func (*Logger) FmtFatal

func (logger *Logger) FmtFatal(vals ...interface{}) string

FmtFatal Formats given strings and returns it for logging purpose

func (*Logger) FmtInfo

func (logger *Logger) FmtInfo(vals ...interface{}) string

FmtInfo Formats given strings and returns it for logging purpose

func (*Logger) FmtNetwork

func (logger *Logger) FmtNetwork(vals ...interface{}) string

FmtNetwork Formats given strings and returns it for logging purpose

func (*Logger) FmtNotice

func (logger *Logger) FmtNotice(vals ...interface{}) string

FmtNotice Formats given strings and returns it for logging purpose

func (*Logger) FmtSys

func (logger *Logger) FmtSys(vals ...interface{}) string

FmtSys Formats given strings and returns it for logging purpose

func (*Logger) FmtVerbose

func (logger *Logger) FmtVerbose(vals ...interface{}) string

FmtVerbose Formats given strings and returns it for logging purpose

func (*Logger) FmtWarn

func (logger *Logger) FmtWarn(vals ...interface{}) string

FmtWarn Formats given strings and returns it for logging purpose

func (*Logger) Info

func (logger *Logger) Info(vals ...interface{})

Info Outputs a log to stdout stream

func (*Logger) Infof

func (logger *Logger) Infof(vals ...interface{})

Infof outputs formmated logging.

This is useful when you need to format the logging message.

[IMPORTANT] FormattedText supports JSON format log output as well.

Example:

logger.Infof("This is a log", "intVar", 123, "stringVar", "aaa", "object", obj)

func (*Logger) Network

func (logger *Logger) Network(vals ...interface{})

Network Outputs a log to stdout stream

func (*Logger) Networkf

func (logger *Logger) Networkf(vals ...interface{})

Networkf outputs formmated logging.

This is useful when you need to format the logging message.

[IMPORTANT] FormattedText supports JSON format log output as well.

Example:

logger.Networkf("This is a log", "intVar", 123, "stringVar", "aaa", "object", obj)

func (*Logger) Notice

func (logger *Logger) Notice(vals ...interface{})

Notice Outputs a log to stdout stream

func (*Logger) Noticef

func (logger *Logger) Noticef(vals ...interface{})

Noticef outputs formmated logging.

This is useful when you need to format the logging message.

[IMPORTANT] FormattedText supports JSON format log output as well.

Example:

logger.Noticef("This is a log", "intVar", 123, "stringVar", "aaa", "object", obj)

func (*Logger) Sys

func (logger *Logger) Sys(vals ...interface{})

Sys Outputs a log to stdout stream

func (*Logger) Sysf

func (logger *Logger) Sysf(vals ...interface{})

Sysf outputs formmated logging.

This is useful when you need to format the logging message.

[IMPORTANT] FormattedText supports JSON format log output as well.

Example:

logger.Sysf("This is a log", "intVar", 123, "stringVar", "aaa", "object", obj)

func (*Logger) Trace

func (logger *Logger) Trace(vals ...interface{})

Trace Outputs a log to stdout stream as Sys level log with stack trace. Useful for debugging

func (*Logger) Verbose

func (logger *Logger) Verbose(vals ...interface{})

Verbose Outputs a log to stdout stream

func (*Logger) Verbosef

func (logger *Logger) Verbosef(vals ...interface{})

Verbosef outputs formmated logging.

This is useful when you need to format the logging message.

[IMPORTANT] FormattedText supports JSON format log output as well.

Example:

logger.Verbosef("This is a log", "intVar", 123, "stringVar", "aaa", "object", obj)

func (*Logger) Warn

func (logger *Logger) Warn(vals ...interface{})

Warn Outputs a log to stdout stream

func (*Logger) Warnf

func (logger *Logger) Warnf(vals ...interface{})

Warnf outputs formmated logging.

This is useful when you need to format the logging message.

[IMPORTANT] FormattedText supports JSON format log output as well.

Example:

logger.Warnf("This is a log", "intVar", 123, "stringVar", "aaa", "object", obj)

func (*Logger) Write

func (logger *Logger) Write(vals ...interface{})

Write outputs a log to stdout stream

Subdirectories

Name Synopsis
..
lib
colorize
msg
std