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 7 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 @@
1 1
 package main
2 2
 
3 3
 import (
4
+	"fmt"
4 5
 	"log"
5 6
 	"net/http"
7
+	"os"
6 8
 
7 9
 	bolt "go.etcd.io/bbolt"
8 10
 
@@ -10,8 +12,37 @@ import (
10 12
 	"gitea.nefixestrada.com/nefix/urlshortener/pkg/handler"
11 13
 )
12 14
 
15
+type logWriter struct {
16
+	File *os.File
17
+}
18
+
19
+func (w *logWriter) Write(b []byte) (int, error) {
20
+	fmt.Print(string(b[:]))
21
+
22
+	return w.File.Write(b)
23
+}
24
+
13 25
 func main() {
14
-	boltDB, err := bolt.Open("urlshortener.db", 0600, nil)
26
+	// Configure the logging
27
+	f, err := os.OpenFile("urlshortener.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
28
+	if err != nil {
29
+		log.Fatalf("error opening log file: %v", err)
30
+	}
31
+	defer func() {
32
+		if err = f.Close(); err != nil {
33
+			log.Fatalf("error closing the log file: %v", err)
34
+		}
35
+	}()
36
+
37
+	w := &logWriter{
38
+		File: f,
39
+	}
40
+
41
+	log.SetOutput(w)
42
+
43
+	// Open the DB and initialize it
44
+	var boltDB *bolt.DB
45
+	boltDB, err = bolt.Open("urlshortener.db", 0600, nil)
15 46
 	if err != nil {
16 47
 		log.Fatalf("error opening the DB: %v", err)
17 48
 	}
@@ -29,6 +60,7 @@ func main() {
29 60
 		log.Fatalf("error initializing the DB: %v", err)
30 61
 	}
31 62
 
63
+	// Start the HTTP server
32 64
 	log.Println("Starting to listen at port :3000")
33 65
 	if err := http.ListenAndServe(":3000", handler.Default(db)); err != nil {
34 66
 		log.Fatalf("error listening: %v", err)

Loading…
Cancel
Save