Browse Source

Added log write support

Now the logs are written in the urlshortener.log file. They
still get printed in the screen
tags/v1.0.1^2
Néfix Estrada 10 months ago
parent
commit
0bfbfa345c
1 changed files with 33 additions and 1 deletions
  1. 33
    1
      cmd/urlshortener/main.go

+ 33
- 1
cmd/urlshortener/main.go View File

@@ -1,8 +1,10 @@
package main

import (
"fmt"
"log"
"net/http"
"os"

bolt "go.etcd.io/bbolt"

@@ -10,8 +12,37 @@ import (
"gitea.nefixestrada.com/nefix/urlshortener/pkg/handler"
)

type logWriter struct {
File *os.File
}

func (w *logWriter) Write(b []byte) (int, error) {
fmt.Print(string(b[:]))

return w.File.Write(b)
}

func main() {
boltDB, err := bolt.Open("urlshortener.db", 0600, nil)
// Configure the logging
f, err := os.OpenFile("urlshortener.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
if err != nil {
log.Fatalf("error opening log file: %v", err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatalf("error closing the log file: %v", err)
}
}()

w := &logWriter{
File: f,
}

log.SetOutput(w)

// Open the DB and initialize it
var boltDB *bolt.DB
boltDB, err = bolt.Open("urlshortener.db", 0600, nil)
if err != nil {
log.Fatalf("error opening the DB: %v", err)
}
@@ -29,6 +60,7 @@ func main() {
log.Fatalf("error initializing the DB: %v", err)
}

// Start the HTTP server
log.Println("Starting to listen at port :3000")
if err := http.ListenAndServe(":3000", handler.Default(db)); err != nil {
log.Fatalf("error listening: %v", err)

Loading…
Cancel
Save