Skip to content

Commit

Permalink
Changed field name from session_name to service_instance_name
Browse files Browse the repository at this point in the history
  • Loading branch information
bhagatvansh committed Oct 26, 2023
1 parent bfe43f5 commit b3d8c91
Show file tree
Hide file tree
Showing 7 changed files with 81 additions and 81 deletions.
4 changes: 2 additions & 2 deletions _nocode/db/migrations/001_base_schema.up.sql
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ CREATE TABLE IF NOT EXISTS app_log
log_time TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT (NOW() AT TIME ZONE ('utc')),
log_level VARCHAR(16) NOT NULL DEFAULT 'info',
service_name VARCHAR(64) NOT NULL DEFAULT 'def_svc',
session_name VARCHAR(64) NOT NULL DEFAULT 'def_svc_instance',
sevice_instance_name VARCHAR(64) NOT NULL DEFAULT 'def_svc_instance',
code VARCHAR(16) NOT NULL DEFAULT '000000',
msg TEXT NOT NULL DEFAULT '_no_msg_supplied_',
more_data jsonb NOT NULL DEFAULT '{}'::jsonb
Expand All @@ -16,7 +16,7 @@ COMMENT ON COLUMN app_log.id IS 'Unique log ID, Primary Key, Auto-incrementing n
COMMENT ON COLUMN app_log.log_time IS 'UTC time when the log occurred. Defaults to "now()"';
COMMENT ON COLUMN app_log.log_level IS 'Severity level - INFO, WARNING, ERROR, PANIC etc.';
COMMENT ON COLUMN app_log.service_name IS 'Name of the service that sent this log (defaults to "def_svc")';
COMMENT ON COLUMN app_log.session_name IS 'Name of the service instance (or Pod Name) that sent this log (defaults to "def_sess")';
COMMENT ON COLUMN app_log.service_instance_name IS 'Name of the service instance (or Pod Name) that sent this log (defaults to "def_svc_instance")';
COMMENT ON COLUMN app_log.code IS 'Unique Code of the log (LMID) - to be sent by the caller (defaults to "000000")';
COMMENT ON COLUMN app_log.msg IS 'Actual log message as text';
COMMENT ON COLUMN app_log.more_data IS 'Anything else that needs to be saved alongside the log entry';
Expand Down
4 changes: 2 additions & 2 deletions _nocode/postman_collection/Bark.postman_collection.json
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@
"header": [],
"body": {
"mode": "raw",
"raw": "{\n \"id\": -100,\n \"logLevel\": \"info\",\n \"serviceName\": \"TestPostman\",\n \"sessionName\": \"testSession\",\n \"code\": \"1KE0H8\",\n \"msg\": \"Shows up in DB or not?\",\n \"moreData\": {\n \"name\":\"vaibhav\"\n }\n}",
"raw": "{\n \"id\": -100,\n \"logLevel\": \"info\",\n \"serviceName\": \"TestPostman\",\n \"serviceInstanceName\": \"testSession\",\n \"code\": \"1KE0H8\",\n \"msg\": \"Shows up in DB or not?\",\n \"moreData\": {\n \"name\":\"vaibhav\"\n }\n}",
"options": {
"raw": {
"language": "json"
Expand Down Expand Up @@ -111,7 +111,7 @@
"header": [],
"body": {
"mode": "raw",
"raw": "[\n {\n \"code\": \"1KE0H8\"\n },\n {\n \"msg\": \"Shows up in DB or not?\"\n },\n {\n \"serviceName\": \"TestPostman\",\n \"sessionName\": \"testSession\",\n \"code\": \"1KE0H9\",\n \"msg\": \"Shows up in DB or not?\",\n \"moreData\": {\n \"name\": \"vaibhav\"\n }\n },\n {\n \"logLevel\": \"error\",\n \"sessionName\": \"testSession\",\n \"code\": \"1KE0I1\",\n \"msg\": \"Shows up in DB or not?\",\n \"moreData\": {\n \"name\": \"vaibhav\"\n }\n },\n {\n \"logLevel\": \"info\",\n \"serviceName\": \"TestPostman\",\n \"sessionName\": \"testSession\",\n \"code\": \"1KE0I2\",\n \"msg\": \"Shows up in DB or not?\",\n \"moreData\": {\n \"name\": \"vaibhav\"\n }\n },\n {\n \"logLevel\": \"info\",\n \"serviceName\": \"TestPostman\",\n \"sessionName\": \"testSession\",\n \"code\": \"1KE0I3\",\n \"msg\": \"Shows up in DB or not?\"\n },\n {\n \"logLevel\": \"info\",\n \"serviceName\": \"TestPostman\",\n \"sessionName\": \"testSession\"\n }\n]",
"raw": "[\n {\n \"code\": \"1KE0H8\"\n },\n {\n \"msg\": \"Shows up in DB or not?\"\n },\n {\n \"serviceName\": \"TestPostman\",\n \"serviceInstanceName\": \"testSession\",\n \"code\": \"1KE0H9\",\n \"msg\": \"Shows up in DB or not?\",\n \"moreData\": {\n \"name\": \"vaibhav\"\n }\n },\n {\n \"logLevel\": \"error\",\n \"serviceInstanceName\": \"testSession\",\n \"code\": \"1KE0I1\",\n \"msg\": \"Shows up in DB or not?\",\n \"moreData\": {\n \"name\": \"vaibhav\"\n }\n },\n {\n \"logLevel\": \"info\",\n \"serviceName\": \"TestPostman\",\n \"serviceInstanceName\": \"testSession\",\n \"code\": \"1KE0I2\",\n \"msg\": \"Shows up in DB or not?\",\n \"moreData\": {\n \"name\": \"vaibhav\"\n }\n },\n {\n \"logLevel\": \"info\",\n \"serviceName\": \"TestPostman\",\n \"serviceInstanceName\": \"testSession\",\n \"code\": \"1KE0I3\",\n \"msg\": \"Shows up in DB or not?\"\n },\n {\n \"logLevel\": \"info\",\n \"serviceName\": \"TestPostman\",\n \"serviceInstanceName\": \"testSession\"\n }\n]",
"options": {
"raw": {
"language": "json"
Expand Down
4 changes: 2 additions & 2 deletions client/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ Any single character in the place of error level in a parsable single log messag
The client can be initialized and used as follows (we explain the options below code sample):

```go
barkClient := client.NewClient("<bark_server_url>", "<default_log_level>", "<default_service_name>", "<session_name>",
barkClient := client.NewClient("<bark_server_url>", "<default_log_level>", "<default_service_name>", "<service_instance_name>",
"<enable_slog", "<enable_bulk_dispatch>")

barkClient.Panic("E#1LPW24 - Panic message")
Expand All @@ -41,7 +41,7 @@ The options that are used for initializing the client are as follows:
- **bark_server_url**: This is the URL of a running bark server. It must end in `/`. For example `http://bark.example.com/` or `http://127.0.0.1:8080/`
- **default_log_level**: When you use `Println` or `Default`, the log message is parsed (rules for prasing are described [here](../_nocode/docs/log-string-parsing-in-bark.md)) and if it does not contain any indication for what the log level is, then the value supplied in this field is used as the log level for sent log message. When using dedicated methods for error levels (e.g. `Panic`, `Error` etc.), the parsed error level is overwritten.
- **default_service_name**: This is the name of the service which is sending the log - so it has to be the name of the program or service which is calling it. In case a blank string is sent, the value against `constants.DefaultLogServiceName` (currently set to `def_svc`) is used.
- **session_name**: This is the name of the calling app's session. This value is supposed to indicate which instance among possibly multiple instances of a service sent a log message. For example, in case of the service being deployed within Kubernetes, it might indicate the service's pod's name. If the value is sent as a blank string, client will try to use the machine's hostname. If it fails to fetch the hostname, a random string will be used instead.
- **service_instance_name**: This is the name of the calling app's session. This value is supposed to indicate which instance among possibly multiple instances of a service sent a log message. For example, in case of the service being deployed within Kubernetes, it might indicate the service's pod's name. If the value is sent as a blank string, client will try to use the machine's hostname. If it fails to fetch the hostname, a random string will be used instead.
- **enable_slog**: This enables [slog](https://go.dev/blog/slog) for the client. When this option is enabled, all logs in addition to being sent to the bark server is also printed on STDOUT of the service.
- **enable_bulk_dispatch**: Setting this to true would enable the client to push all the requests being received in a channel and start using it. It improves the overall performance of the client sending log entries to the server.

Expand Down
90 changes: 45 additions & 45 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ type Config struct {
BaseUrl string
ErrorLevel string
ServiceName string
SessionName string
ServiceInstanceName string
BulkSend bool
Slogger *slog.Logger
AlertWebhook webhook
Expand All @@ -36,8 +36,8 @@ type Config struct {
// parseMessage extracts LMID (Log Message Identifier) if a valid LMID exists in message string otherwise.
func (c *Config) parseMessage(msg string) models.BarkLog {
l := models.BarkLog{
ServiceName: c.ServiceName,
SessionName: c.SessionName,
ServiceName: c.ServiceName,
ServiceInstanceName: c.ServiceInstanceName,
}

if len(msg) < 6 {
Expand Down Expand Up @@ -368,13 +368,13 @@ func (c *Config) Raw(rawLog RawLog, returnError bool) error {
}

l := models.BarkLog{
LogTime: rawLog.LogTime,
LogLevel: rawLog.LogLevel,
ServiceName: rawLog.ServiceName,
SessionName: rawLog.SessionName,
Code: rawLog.Code,
Message: rawLog.Message,
MoreData: moreData,
LogTime: rawLog.LogTime,
LogLevel: rawLog.LogLevel,
ServiceName: rawLog.ServiceName,
ServiceInstanceName: rawLog.ServiceInstanceName,
Code: rawLog.Code,
Message: rawLog.Message,
MoreData: moreData,
}

c.dispatchLogMessage(l)
Expand Down Expand Up @@ -520,13 +520,13 @@ func NewSloggerClient(defaultLogLevel string) *Config {
slogger := newSlogger(os.Stdout)

return &Config{
serverMode: constants.ClientServerUsageModeDisabled,
BaseUrl: constants.DisabledServerUrl,
ErrorLevel: defaultLogLevel,
ServiceName: "",
SessionName: "",
Slogger: slogger,
BulkSend: false,
serverMode: constants.ClientServerUsageModeDisabled,
BaseUrl: constants.DisabledServerUrl,
ErrorLevel: defaultLogLevel,
ServiceName: "",
ServiceInstanceName: "",
Slogger: slogger,
BulkSend: false,
}
}

Expand All @@ -545,7 +545,7 @@ func NewSloggerClient(defaultLogLevel string) *Config {
// string. If an empty string is given, the function will print a warning message and use
// constants.DefaultLogServiceName as the default value.
//
// The sessName parameter is the name of the session that is logging. It must be a non-empty
// The svcInstName parameter is the name of the service instance that is logging. It must be a non-empty
// string. If an empty string is given, the function will print a warning message and use
// appRuntime.SessionName as the default value.
//
Expand All @@ -557,20 +557,20 @@ func NewSloggerClient(defaultLogLevel string) *Config {
// of logs to the remote server. If true, the function will start a goroutine that periodically
// sends all the buffered logs to the server. If false, the logs will be sent individually as
// they are generated.
func NewClient(url, defaultLogLvl, svcName, sessName string, enableSlog bool, enableBulkSend bool) *Config {
func NewClient(url, defaultLogLvl, svcName, svcInstName string, enableSlog bool, enableBulkSend bool) *Config {
if !isValid(defaultLogLvl) {
fmt.Printf("L#1LPYG2 - %v is not an acceptable log level. %v will be used as the default log level", defaultLogLvl, constants.DefaultLogLevel)
defaultLogLvl = constants.DefaultLogLevel
}

if strings.TrimSpace(svcName) == "" {
sessName = constants.DefaultLogServiceName
fmt.Printf("L#1L3WBF - Blank service name supplied. Using %v as Session Name", sessName)
svcName = constants.DefaultLogServiceName
fmt.Printf("L#1L3WBF - Blank service name supplied. Using %v as Service Name", svcName)
}

if strings.TrimSpace(sessName) == "" {
sessName = appRuntime.SessionName
fmt.Printf("L#1L3WBF - Blank session name supplied. Using %v as Session Name", sessName)
if strings.TrimSpace(svcInstName) == "" {
svcInstName = appRuntime.SessionName
fmt.Printf("L#1L3WBF - Blank instance name supplied. Using %v as Service Instance Name", svcInstName)
}

//Wg.Add(1)
Expand All @@ -588,13 +588,13 @@ func NewClient(url, defaultLogLvl, svcName, sessName string, enableSlog bool, en
}

return &Config{
serverMode: constants.ClientServerUsageModeRemoteServer,
BaseUrl: url,
ErrorLevel: defaultLogLvl,
ServiceName: svcName,
SessionName: sessName,
Slogger: slogger,
BulkSend: enableBulkSend,
serverMode: constants.ClientServerUsageModeRemoteServer,
BaseUrl: url,
ErrorLevel: defaultLogLvl,
ServiceName: svcName,
ServiceInstanceName: svcInstName,
Slogger: slogger,
BulkSend: enableBulkSend,
}
}

Expand All @@ -613,27 +613,27 @@ func NewClient(url, defaultLogLvl, svcName, sessName string, enableSlog bool, en
// string. If an empty string is given, the function will print a warning message and use
// constants.DefaultLogServiceName as the default value.
//
// The sessName parameter is the name of the session that is logging. It must be a non-empty
// The svcInstName parameter is the name of the service instance that is logging. It must be a non-empty
// string. If an empty string is given, the function will print a warning message and use
// appRuntime.SessionName as the default value.
//
// The enableSlog parameter is a boolean flag that indicates whether to enable slog logging
// to standard output. If true, the function will create and assign a new slog.Logger object
// to the Config object. If false, the Config object will have a nil Slogger field.
func NewClientWithServer(dbUrl, defaultLogLvl, svcName, sessName string, enableSlog bool) *Config {
func NewClientWithServer(dbUrl, defaultLogLvl, svcName, svcInstName string, enableSlog bool) *Config {
if !isValid(defaultLogLvl) {
fmt.Printf("L#1M1XXN - %v is not an acceptable log level. %v will be used as the default log level", defaultLogLvl, constants.DefaultLogLevel)
defaultLogLvl = constants.DefaultLogLevel
}

if strings.TrimSpace(svcName) == "" {
sessName = constants.DefaultLogServiceName
fmt.Printf("L#1M1XY9 - Blank service name supplied. Using %v as Session Name", sessName)
svcName = constants.DefaultLogServiceName
fmt.Printf("L#1M1XY9 - Blank service name supplied. Using %v as Service Name", svcName)
}

if strings.TrimSpace(sessName) == "" {
sessName = appRuntime.SessionName
fmt.Printf("L#1M1XZH - Blank session name supplied. Using %v as Session Name", sessName)
if strings.TrimSpace(svcInstName) == "" {
svcInstName = appRuntime.SessionName
fmt.Printf("L#1M1XZH - Blank instance name supplied. Using %v as Service Instance Name", svcInstName)
}

var slogger *slog.Logger
Expand Down Expand Up @@ -665,13 +665,13 @@ func NewClientWithServer(dbUrl, defaultLogLvl, svcName, sessName string, enableS
go dbLogWriter.KeepSavingLogs()

return &Config{
serverMode: constants.ClientServerUsageModeEmbedded,
BaseUrl: constants.DisabledServerUrl,
ErrorLevel: defaultLogLvl,
ServiceName: svcName,
SessionName: sessName,
Slogger: slogger,
BulkSend: false,
serverMode: constants.ClientServerUsageModeEmbedded,
BaseUrl: constants.DisabledServerUrl,
ErrorLevel: defaultLogLvl,
ServiceName: svcName,
ServiceInstanceName: svcInstName,
Slogger: slogger,
BulkSend: false,
}
}

Expand Down
14 changes: 7 additions & 7 deletions client/rawlog_struct.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ import (
)

type RawLog struct {
LogTime time.Time
LogLevel string
ServiceName string
SessionName string
Code string
Message string
MoreData any
LogTime time.Time
LogLevel string
ServiceName string
ServiceInstanceName string
Code string
Message string
MoreData any
}
2 changes: 1 addition & 1 deletion constants/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const (
DefaultLogLevel = "INFO"
DefaultLogMessage = "_no_msg_supplied_"
DefaultLogServiceName = "def_svc"
DefaultLogSessionName = "def_sess"
DefaultLogSessionName = "def_svc_instance"
)

const (
Expand Down
44 changes: 22 additions & 22 deletions models/barklog.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ import (

// BarkLog is a struct representing a log in Bark
type BarkLog struct {
Id int64 `db:"id" json:"id"`
LogTime time.Time `db:"log_time" json:"logTime"`
LogLevel string `db:"log_level" json:"logLevel"`
ServiceName string `db:"service_name" json:"serviceName"`
SessionName string `db:"session_name" json:"sessionName"`
Code string `db:"code" json:"code"`
Message string `db:"msg" json:"msg"`
MoreData jsonObject.Typ `db:"more_data" json:"moreData"`
Id int64 `db:"id" json:"id"`
LogTime time.Time `db:"log_time" json:"logTime"`
LogLevel string `db:"log_level" json:"logLevel"`
ServiceName string `db:"service_name" json:"serviceName"`
ServiceInstanceName string `db:"service_instance_name" json:"serviceInstanceName"`
Code string `db:"code" json:"code"`
Message string `db:"msg" json:"msg"`
MoreData jsonObject.Typ `db:"more_data" json:"moreData"`
}

// ValidateForInsert checks for missing values in the incoming BarkLog's fields.
Expand All @@ -39,8 +39,8 @@ func (b BarkLog) ValidateForInsert() (BarkLog, error) {
if strings.TrimSpace(b.ServiceName) == "" {
b.ServiceName = constants.DefaultLogServiceName
}
if strings.TrimSpace(b.SessionName) == "" {
b.SessionName = constants.DefaultLogSessionName
if strings.TrimSpace(b.ServiceInstanceName) == "" {
b.ServiceInstanceName = constants.DefaultLogSessionName
}

if strings.TrimSpace(b.Code) == "" && strings.TrimSpace(b.Message) == "" {
Expand All @@ -65,7 +65,7 @@ func (b BarkLog) ValidateForInsert() (BarkLog, error) {

func (b BarkLog) String() string {
return fmt.Sprintf("Id: %v | LogTime: %v | LogLevel: %v | AppName: %v | SessionName: %v | Code: %v | Message: %v | MoreData: %v \n",
b.Id, b.LogTime, b.LogLevel, b.ServiceName, b.SessionName, b.Code, b.Message, b.MoreData)
b.Id, b.LogTime, b.LogLevel, b.ServiceName, b.ServiceInstanceName, b.Code, b.Message, b.MoreData)
}

type BarkLogDao struct{}
Expand All @@ -79,7 +79,7 @@ func (bld *BarkLogDao) Insert(l BarkLog) error {
query := `
INSERT INTO app_log (
log_time, log_level, service_name,
session_name, code, msg,
service_instance_name, code, msg,
more_data
)
VALUES (
Expand All @@ -89,7 +89,7 @@ func (bld *BarkLogDao) Insert(l BarkLog) error {
)`

_, err := resources.BarkDb.Client.Exec(context.Background(), query, l.LogTime, l.LogLevel, l.ServiceName,
l.SessionName, l.Code, l.Message,
l.ServiceInstanceName, l.Code, l.Message,
l.MoreData)

if err != nil {
Expand All @@ -102,27 +102,27 @@ func (bld *BarkLogDao) Insert(l BarkLog) error {
// This acts as a checkpoint that everything is working as expected in the DB connection department.
func (bld *BarkLogDao) InsertServerStartedLog() error {
return bld.Insert(BarkLog{
LogTime: time.Now().UTC(),
LogLevel: constants.Info,
ServiceName: "Bark Server",
SessionName: appRuntime.SessionName,
Code: "1LQ2X3",
Message: "Server started",
MoreData: jsonObject.EmptyNotNullJsonObject(),
LogTime: time.Now().UTC(),
LogLevel: constants.Info,
ServiceName: "Bark Server",
ServiceInstanceName: appRuntime.SessionName,
Code: "1LQ2X3",
Message: "Server started",
MoreData: jsonObject.EmptyNotNullJsonObject(),
})
}

// InsertBatch sends a batch of logs to the DB.
func (bld *BarkLogDao) InsertBatch(l []BarkLog) error {
batchOfBarkLog := [][]any{}
for i := 0; i < len(l); i++ {
batchElement := []any{l[i].LogTime, l[i].LogLevel, l[i].ServiceName, l[i].SessionName,
batchElement := []any{l[i].LogTime, l[i].LogLevel, l[i].ServiceName, l[i].ServiceInstanceName,
l[i].Code, l[i].Message, l[i].MoreData}
batchOfBarkLog = append(batchOfBarkLog, batchElement)
}

_, err := resources.BarkDb.Client.CopyFrom(context.Background(), pgx.Identifier{"app_log"},
[]string{"log_time", "log_level", "service_name", "session_name", "code", "msg", "more_data"}, pgx.CopyFromRows(batchOfBarkLog))
[]string{"log_time", "log_level", "service_name", "service_instance_name", "code", "msg", "more_data"}, pgx.CopyFromRows(batchOfBarkLog))

if err != nil {
return fmt.Errorf("E#1KSPLS - error while inserting batch: %w", err)
Expand Down

0 comments on commit b3d8c91

Please sign in to comment.