Browse Source

fix: log not print the right row number issue

pull/7/head
konenet 3 years ago
parent
commit
df13a9600f
  1. 6
      api/v1/file_controller.go
  2. 6
      api/v1/message_controller.go
  3. 4
      api/v1/user_controller.go
  4. 8
      cmd/main.go
  5. 6
      internal/kafka/consumer.go
  6. 4
      internal/kafka/producer.go
  7. 4
      internal/router/router.go
  8. 2
      internal/router/socket.go
  9. 4
      internal/server/client.go
  10. 14
      internal/server/server.go
  11. 2
      internal/service/message_service.go
  12. 10
      internal/service/user_service.go
  13. 24
      pkg/global/log/logger.go

6
api/v1/file_controller.go

@ -17,7 +17,7 @@ import (
// 前端通过文件名称获取文件流,显示文件 // 前端通过文件名称获取文件流,显示文件
func GetFile(c *gin.Context) { func GetFile(c *gin.Context) {
fileName := c.Param("fileName") fileName := c.Param("fileName")
log.Info(fileName) log.Logger.Info(fileName)
data, _ := ioutil.ReadFile(config.GetConfig().StaticPath.FilePath + fileName) data, _ := ioutil.ReadFile(config.GetConfig().StaticPath.FilePath + fileName)
c.Writer.Write(data) c.Writer.Write(data)
} }
@ -35,8 +35,8 @@ func SaveFile(c *gin.Context) {
newFileName := namePreffix + suffix newFileName := namePreffix + suffix
log.Info("file", log.Any("file name", config.GetConfig().StaticPath.FilePath+newFileName)) log.Logger.Info("file", log.Any("file name", config.GetConfig().StaticPath.FilePath+newFileName))
log.Info("userUuid", log.Any("userUuid name", userUuid)) log.Logger.Info("userUuid", log.Any("userUuid name", userUuid))
c.SaveUploadedFile(file, config.GetConfig().StaticPath.FilePath+newFileName) c.SaveUploadedFile(file, config.GetConfig().StaticPath.FilePath+newFileName)
err := service.UserService.ModifyUserAvatar(newFileName, userUuid) err := service.UserService.ModifyUserAvatar(newFileName, userUuid)

6
api/v1/message_controller.go

@ -13,13 +13,13 @@ import (
// 获取消息列表 // 获取消息列表
func GetMessage(c *gin.Context) { func GetMessage(c *gin.Context) {
log.Info(c.Query("uuid")) log.Logger.Info(c.Query("uuid"))
var messageRequest request.MessageRequest var messageRequest request.MessageRequest
err := c.BindQuery(&messageRequest) err := c.BindQuery(&messageRequest)
if nil != err { if nil != err {
log.Error("bindQueryError", log.Any("bindQueryError", err)) log.Logger.Error("bindQueryError", log.Any("bindQueryError", err))
} }
log.Info("messageRequest params: ", log.Any("messageRequest", messageRequest)) log.Logger.Info("messageRequest params: ", log.Any("messageRequest", messageRequest))
messages, err := service.MessageService.GetMessages(messageRequest) messages, err := service.MessageService.GetMessages(messageRequest)
if err != nil { if err != nil {

4
api/v1/user_controller.go

@ -16,7 +16,7 @@ func Login(c *gin.Context) {
var user model.User var user model.User
// c.BindJSON(&user) // c.BindJSON(&user)
c.ShouldBindJSON(&user) c.ShouldBindJSON(&user)
log.Debug("user", log.Any("user", user)) log.Logger.Debug("user", log.Any("user", user))
if service.UserService.Login(&user) { if service.UserService.Login(&user) {
c.JSON(http.StatusOK, response.SuccessMsg(user)) c.JSON(http.StatusOK, response.SuccessMsg(user))
@ -41,7 +41,7 @@ func Register(c *gin.Context) {
func ModifyUserInfo(c *gin.Context) { func ModifyUserInfo(c *gin.Context) {
var user model.User var user model.User
c.ShouldBindJSON(&user) c.ShouldBindJSON(&user)
log.Debug("user", log.Any("user", user)) log.Logger.Debug("user", log.Any("user", user))
if err := service.UserService.ModifyUserInfo(&user); err != nil { if err := service.UserService.ModifyUserInfo(&user); err != nil {
c.JSON(http.StatusOK, response.FailMsg(err.Error())) c.JSON(http.StatusOK, response.FailMsg(err.Error()))
return return

8
cmd/main.go

@ -9,13 +9,11 @@ import (
"chat-room/pkg/global/log" "chat-room/pkg/global/log"
"net/http" "net/http"
"time" "time"
"go.uber.org/zap"
) )
func main() { func main() {
log.InitLogger(config.GetConfig().Log.Path, config.GetConfig().Log.Level) log.InitLogger(config.GetConfig().Log.Path, config.GetConfig().Log.Level)
log.Info("config", zap.Any("config", config.GetConfig())) log.Logger.Info("config", log.Any("config", config.GetConfig()))
if config.GetConfig().MsgChannelType.ChannelType == constant.KAFKA { if config.GetConfig().MsgChannelType.ChannelType == constant.KAFKA {
kafka.InitProducer(config.GetConfig().MsgChannelType.KafkaTopic, config.GetConfig().MsgChannelType.KafkaHosts) kafka.InitProducer(config.GetConfig().MsgChannelType.KafkaTopic, config.GetConfig().MsgChannelType.KafkaHosts)
@ -23,7 +21,7 @@ func main() {
go kafka.ConsumerMsg(server.ConsumerKafkaMsg) go kafka.ConsumerMsg(server.ConsumerKafkaMsg)
} }
log.Info("start server", zap.String("start", "start web sever...")) log.Logger.Info("start server", log.String("start", "start web sever..."))
newRouter := router.NewRouter() newRouter := router.NewRouter()
@ -38,6 +36,6 @@ func main() {
} }
err := s.ListenAndServe() err := s.ListenAndServe()
if nil != err { if nil != err {
log.Error("server error", zap.Any("serverError", err)) log.Logger.Error("server error", log.Any("serverError", err))
} }
} }

6
internal/kafka/consumer.go

@ -15,12 +15,12 @@ func InitConsumer(hosts string) {
config := sarama.NewConfig() config := sarama.NewConfig()
client, err := sarama.NewClient(strings.Split(hosts, ","), config) client, err := sarama.NewClient(strings.Split(hosts, ","), config)
if nil != err { if nil != err {
log.Error("init kafka consumer client error", log.Any("init kafka consumer client error", err.Error())) log.Logger.Error("init kafka consumer client error", log.Any("init kafka consumer client error", err.Error()))
} }
consumer, err = sarama.NewConsumerFromClient(client) consumer, err = sarama.NewConsumerFromClient(client)
if nil != err { if nil != err {
log.Error("init kafka consumer error", log.Any("init kafka consumer error", err.Error())) log.Logger.Error("init kafka consumer error", log.Any("init kafka consumer error", err.Error()))
} }
} }
@ -28,7 +28,7 @@ func InitConsumer(hosts string) {
func ConsumerMsg(callBack ConsumerCallback) { func ConsumerMsg(callBack ConsumerCallback) {
partitionConsumer, err := consumer.ConsumePartition(topic, 0, sarama.OffsetNewest) partitionConsumer, err := consumer.ConsumePartition(topic, 0, sarama.OffsetNewest)
if nil != err { if nil != err {
log.Error("iConsumePartition error", log.Any("ConsumePartition error", err.Error())) log.Logger.Error("iConsumePartition error", log.Any("ConsumePartition error", err.Error()))
return return
} }

4
internal/kafka/producer.go

@ -16,12 +16,12 @@ func InitProducer(topicInput, hosts string) {
config.Producer.Compression = sarama.CompressionGZIP config.Producer.Compression = sarama.CompressionGZIP
client, err := sarama.NewClient(strings.Split(hosts, ","), config) client, err := sarama.NewClient(strings.Split(hosts, ","), config)
if nil != err { if nil != err {
log.Error("init kafka client error", log.Any("init kafka client error", err.Error())) log.Logger.Error("init kafka client error", log.Any("init kafka client error", err.Error()))
} }
producer, err = sarama.NewAsyncProducerFromClient(client) producer, err = sarama.NewAsyncProducerFromClient(client)
if nil != err { if nil != err {
log.Error("init kafka async client error", log.Any("init kafka async client error", err.Error())) log.Logger.Error("init kafka async client error", log.Any("init kafka async client error", err.Error()))
} }
} }

4
internal/router/router.go

@ -64,7 +64,7 @@ func Cors() gin.HandlerFunc {
defer func() { defer func() {
if err := recover(); err != nil { if err := recover(); err != nil {
log.Error("HttpError", zap.Any("HttpError", err)) log.Logger.Error("HttpError", zap.Any("HttpError", err))
} }
}() }()
@ -75,7 +75,7 @@ func Cors() gin.HandlerFunc {
func Recovery(c *gin.Context) { func Recovery(c *gin.Context) {
defer func() { defer func() {
if r := recover(); r != nil { if r := recover(); r != nil {
log.Error("gin catch error: ", log.Any("gin catch error: ", r)) log.Logger.Error("gin catch error: ", log.Any("gin catch error: ", r))
c.JSON(http.StatusOK, response.FailMsg("系统内部错误")) c.JSON(http.StatusOK, response.FailMsg("系统内部错误"))
} }
}() }()

2
internal/router/socket.go

@ -21,7 +21,7 @@ func RunSocekt(c *gin.Context) {
if user == "" { if user == "" {
return return
} }
log.Info("newUser", zap.String("newUser", user)) log.Logger.Info("newUser", zap.String("newUser", user))
ws, err := upGrader.Upgrade(c.Writer, c.Request, nil) ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
if err != nil { if err != nil {
return return

4
internal/server/client.go

@ -27,7 +27,7 @@ func (c *Client) Read() {
c.Conn.PongHandler() c.Conn.PongHandler()
_, message, err := c.Conn.ReadMessage() _, message, err := c.Conn.ReadMessage()
if err != nil { if err != nil {
log.Error("client read message error", log.Any("client read message error", err.Error())) log.Logger.Error("client read message error", log.Any("client read message error", err.Error()))
MyServer.Ungister <- c MyServer.Ungister <- c
c.Conn.Close() c.Conn.Close()
break break
@ -44,7 +44,7 @@ func (c *Client) Read() {
} }
pongByte, err2 := proto.Marshal(pong) pongByte, err2 := proto.Marshal(pong)
if nil != err2 { if nil != err2 {
log.Error("client marshal message error", log.Any("client marshal message error", err2.Error())) log.Logger.Error("client marshal message error", log.Any("client marshal message error", err2.Error()))
} }
c.Conn.WriteMessage(websocket.BinaryMessage, pongByte) c.Conn.WriteMessage(websocket.BinaryMessage, pongByte)
} else { } else {

14
internal/server/server.go

@ -42,11 +42,11 @@ func ConsumerKafkaMsg(data []byte) {
} }
func (s *Server) Start() { func (s *Server) Start() {
log.Info("start server", log.Any("start server", "start server...")) log.Logger.Info("start server", log.Any("start server", "start server..."))
for { for {
select { select {
case conn := <-s.Register: case conn := <-s.Register:
log.Info("login", log.Any("login", "new user login in"+conn.Name)) log.Logger.Info("login", log.Any("login", "new user login in"+conn.Name))
s.Clients[conn.Name] = conn s.Clients[conn.Name] = conn
msg := &protocol.Message{ msg := &protocol.Message{
From: "System", From: "System",
@ -57,7 +57,7 @@ func (s *Server) Start() {
conn.Send <- protoMsg conn.Send <- protoMsg
case conn := <-s.Ungister: case conn := <-s.Ungister:
log.Info("loginout", log.Any("loginout", conn.Name)) log.Logger.Info("loginout", log.Any("loginout", conn.Name))
if _, ok := s.Clients[conn.Name]; ok { if _, ok := s.Clients[conn.Name]; ok {
close(conn.Send) close(conn.Send)
delete(s.Clients, conn.Name) delete(s.Clients, conn.Name)
@ -99,7 +99,7 @@ func (s *Server) Start() {
} else { } else {
// 无对应接受人员进行广播 // 无对应接受人员进行广播
for id, conn := range s.Clients { for id, conn := range s.Clients {
log.Info("allUser", log.Any("allUser", id)) log.Logger.Info("allUser", log.Any("allUser", id))
select { select {
case conn.Send <- message: case conn.Send <- message:
@ -161,12 +161,12 @@ func saveMessage(message *protocol.Message) {
dataBuffer, dataErr := base64.StdEncoding.DecodeString(content) dataBuffer, dataErr := base64.StdEncoding.DecodeString(content)
if dataErr != nil { if dataErr != nil {
log.Error("transfer base64 to file error", log.String("transfer base64 to file error", dataErr.Error())) log.Logger.Error("transfer base64 to file error", log.String("transfer base64 to file error", dataErr.Error()))
return return
} }
err := ioutil.WriteFile(config.GetConfig().StaticPath.FilePath+url, dataBuffer, 0666) err := ioutil.WriteFile(config.GetConfig().StaticPath.FilePath+url, dataBuffer, 0666)
if err != nil { if err != nil {
log.Error("write file error", log.String("write file error", err.Error())) log.Logger.Error("write file error", log.String("write file error", err.Error()))
return return
} }
message.Url = url message.Url = url
@ -182,7 +182,7 @@ func saveMessage(message *protocol.Message) {
url := uuid.New().String() + "." + fileSuffix url := uuid.New().String() + "." + fileSuffix
err := ioutil.WriteFile(config.GetConfig().StaticPath.FilePath+url, message.File, 0666) err := ioutil.WriteFile(config.GetConfig().StaticPath.FilePath+url, message.File, 0666)
if err != nil { if err != nil {
log.Error("write file error", log.String("write file error", err.Error())) log.Logger.Error("write file error", log.String("write file error", err.Error()))
return return
} }
message.Url = url message.Url = url

2
internal/service/message_service.go

@ -81,7 +81,7 @@ func (m *messageService) SaveMessage(message protocol.Message) {
var fromUser model.User var fromUser model.User
db.Find(&fromUser, "uuid = ?", message.From) db.Find(&fromUser, "uuid = ?", message.From)
if NULL_ID == fromUser.Id { if NULL_ID == fromUser.Id {
log.Error("SaveMessage not find from user", log.Any("SaveMessage not find from user", fromUser.Id)) log.Logger.Error("SaveMessage not find from user", log.Any("SaveMessage not find from user", fromUser.Id))
return return
} }

10
internal/service/user_service.go

@ -35,12 +35,12 @@ func (u *userService) Register(user *model.User) error {
func (u *userService) Login(user *model.User) bool { func (u *userService) Login(user *model.User) bool {
pool.GetDB().AutoMigrate(&user) pool.GetDB().AutoMigrate(&user)
log.Debug("user", log.Any("user in service", user)) log.Logger.Debug("user", log.Any("user in service", user))
db := pool.GetDB() db := pool.GetDB()
var queryUser *model.User var queryUser *model.User
db.First(&queryUser, "username = ?", user.Username) db.First(&queryUser, "username = ?", user.Username)
log.Debug("queryUser", log.Any("queryUser", queryUser)) log.Logger.Debug("queryUser", log.Any("queryUser", queryUser))
user.Uuid = queryUser.Uuid user.Uuid = queryUser.Uuid
@ -51,7 +51,7 @@ func (u *userService) ModifyUserInfo(user *model.User) error {
var queryUser *model.User var queryUser *model.User
db := pool.GetDB() db := pool.GetDB()
db.First(&queryUser, "username = ?", user.Username) db.First(&queryUser, "username = ?", user.Username)
log.Debug("queryUser", log.Any("queryUser", queryUser)) log.Logger.Debug("queryUser", log.Any("queryUser", queryUser))
var nullId int32 = 0 var nullId int32 = 0
if nullId == queryUser.Id { if nullId == queryUser.Id {
return errors.New("用户不存在") return errors.New("用户不存在")
@ -107,7 +107,7 @@ func (u *userService) AddFriend(userFriendRequest *request.FriendRequest) error
var queryUser *model.User var queryUser *model.User
db := pool.GetDB() db := pool.GetDB()
db.First(&queryUser, "uuid = ?", userFriendRequest.Uuid) db.First(&queryUser, "uuid = ?", userFriendRequest.Uuid)
log.Debug("queryUser", log.Any("queryUser", queryUser)) log.Logger.Debug("queryUser", log.Any("queryUser", queryUser))
var nullId int32 = 0 var nullId int32 = 0
if nullId == queryUser.Id { if nullId == queryUser.Id {
return errors.New("用户不存在") return errors.New("用户不存在")
@ -132,7 +132,7 @@ func (u *userService) AddFriend(userFriendRequest *request.FriendRequest) error
db.AutoMigrate(&userFriend) db.AutoMigrate(&userFriend)
db.Save(&userFriend) db.Save(&userFriend)
log.Debug("userFriend", log.Any("userFriend", userFriend)) log.Logger.Debug("userFriend", log.Any("userFriend", userFriend))
return nil return nil
} }

24
pkg/global/log/log.go → pkg/global/log/logger.go

@ -11,7 +11,7 @@ import (
type Field = zap.Field type Field = zap.Field
var ( var (
log *zap.Logger Logger *zap.Logger
String = zap.String String = zap.String
Any = zap.Any Any = zap.Any
Int = zap.Int Int = zap.Int
@ -22,17 +22,17 @@ var (
// InitLogger("./logs/chat.log", "debug") // InitLogger("./logs/chat.log", "debug")
// } // }
func Debug(msg string, fields ...Field) { // func Debug(msg string, fields ...Field) {
log.Debug(msg, fields...) // Logger.Debug(msg, fields...)
} // }
func Info(msg string, fields ...Field) { // func Info(msg string, fields ...Field) {
log.Info(msg, fields...) // Logger.Info(msg, fields...)
} // }
func Error(msg string, fields ...Field) { // func Error(msg string, fields ...Field) {
log.Error(msg, fields...) // Logger.Error(msg, fields...)
} // }
// logpath 日志文件路径 // logpath 日志文件路径
// loglevel 日志级别 // loglevel 日志级别
@ -99,6 +99,6 @@ func InitLogger(logpath string, loglevel string) {
// 设置初始化字段,如:添加一个服务器名称 // 设置初始化字段,如:添加一个服务器名称
filed := zap.Fields(zap.String("application", "chat-room")) filed := zap.Fields(zap.String("application", "chat-room"))
// 构造日志 // 构造日志
log = zap.New(core, caller, development, filed) Logger = zap.New(core, caller, development, filed)
log.Info("Logger init success") Logger.Info("Logger init success")
} }
Loading…
Cancel
Save