github.com/readium/readium-lcp-server@v0.0.0-20240509124024-799e77a0bbd6/logging/logging.go (about)

     1  // Copyright 2023 European Digital Reading Lab. All rights reserved.
     2  // Licensed to the Readium Foundation under one or more contributor license agreements.
     3  // Use of this source code is governed by a BSD-style license
     4  // that can be found in the LICENSE file exposed on Github (readium) in the project repository.
     5  
     6  package logging
     7  
     8  import (
     9  	"errors"
    10  	"log"
    11  	"os"
    12  	"time"
    13  
    14  	"github.com/readium/readium-lcp-server/config"
    15  	"github.com/slack-go/slack"
    16  )
    17  
    18  var (
    19  	LogFile        *log.Logger
    20  	SlackApi       *slack.Client
    21  	SlackChannelID string
    22  )
    23  
    24  // Init inits the log file and opens it
    25  func Init(logging config.Logging) error {
    26  
    27  	//logPath string, cm bool
    28  	if logging.Directory != "" {
    29  		log.Println("Open log file as " + logging.Directory)
    30  		file, err := os.OpenFile(logging.Directory, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
    31  		if err != nil {
    32  			return err
    33  		}
    34  
    35  		LogFile = log.New(file, "", log.LUTC)
    36  	}
    37  	if logging.SlackToken != "" && logging.SlackChannelID != "" {
    38  		log.Println("Init Slack connection")
    39  		SlackApi = slack.New(logging.SlackToken)
    40  		if SlackApi == nil {
    41  			return errors.New("error creating a Slack connector")
    42  		}
    43  		SlackChannelID = logging.SlackChannelID
    44  	}
    45  	return nil
    46  }
    47  
    48  // Print writes a message to the log file / Slack
    49  func Print(message string) {
    50  	// log on stdout
    51  	log.Print(message)
    52  
    53  	// log on a file
    54  	if LogFile != nil {
    55  		currentTime := time.Now().UTC().Format(time.RFC3339)
    56  		LogFile.Println(currentTime + "\t" + message)
    57  	}
    58  
    59  	// log on Slack
    60  	if SlackApi != nil {
    61  		_, _, err := SlackApi.PostMessage(SlackChannelID, slack.MsgOptionText(message, false))
    62  		if err != nil {
    63  			log.Printf("Error sending Slack msg, %v", err)
    64  		}
    65  	}
    66  }