Skip to content

Instantly share code, notes, and snippets.

@Formergg
Created March 11, 2021 04:23
Show Gist options
  • Save Formergg/00e66dd23a76d9f2e394ac5e312c74a7 to your computer and use it in GitHub Desktop.
Save Formergg/00e66dd23a76d9f2e394ac5e312c74a7 to your computer and use it in GitHub Desktop.
打印日志文件示例代码
# Use the official golang image to create a build artifact
FROM golang:1.13 as builder
# Create app directory
RUN mkdir /app
# Add file to /app/
ADD . /app/
# Build the binary
WORKDIR /app
RUN go get -u github.com/sirupsen/logrus
RUN go get -u github.com/lestrrat-go/file-rotatelogs
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .
# Run service on container startup
FROM alpine:latest
WORKDIR /app
COPY --from=builder /app/main .
CMD ["/app/main"]
package main
import (
"fmt"
"log"
"net/http"
"os"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"github.com/sirupsen/logrus"
)
func init() {
// 创建文件日志,按天分割,日志文件仅保留一周
w, err := rotatelogs.New("/logs/service.%Y%m%d.log")
if err != nil {
panic(err)
}
// 设置日志
logrus.SetOutput(w)
logrus.SetFormatter(&logrus.JSONFormatter{})
logrus.SetReportCaller(true)
}
func handler(w http.ResponseWriter, r *http.Request) {
t := r.URL.Query().Get("type")
errorMsg := fmt.Sprintf("receive a request. this is [%s] log\n", t)
switch t {
case "error":
logrus.Errorln(errorMsg)
case "warn":
logrus.Warnln(errorMsg)
case "info":
logrus.Infoln(errorMsg)
case "debug":
logrus.Debugln(errorMsg)
case "stdout":
fmt.Fprintf(os.Stdout, errorMsg)
case "stderr":
fmt.Fprintf(os.Stderr, errorMsg)
default:
}
// 输出响应
fmt.Fprintf(w, "Hello, Welcome to CloudBase!\n")
fmt.Fprintln(w, errorMsg)
}
func main() {
http.HandleFunc("/", handler)
port := os.Getenv("PORT")
if port == "" {
port = "80"
}
fmt.Fprintf(os.Stdout, "start service\n")
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment