Home > Database > Mysql Tutorial > body text

How to develop a simple log management system using MySQL and Go language

王林
Release: 2023-09-21 09:05:14
Original
859 people have browsed it

How to develop a simple log management system using MySQL and Go language

How to use MySQL and Go language to develop a simple log management system

Introduction:
Log is an important component often used in software development. It can help us track problems, record user operations, monitor system performance, etc. In this article, I will teach you how to develop a simple log management system by combining MySQL and Go language, and provide specific code examples.

1. Environment setup
Before we start, we need to set up the development environment first. First, make sure you have installed the MySQL database and created the corresponding log table. Secondly, install the latest version of the Go language development environment to ensure that your code can run correctly.

2. Create the project

  1. Create the project directory and initialize go mod in it:
$ mkdir log_management_system
$ cd log_management_system
$ go mod init log_management_system
Copy after login
  1. Create a main.go file, And open the editor, we will write the main program in this file.

3. Connect to MySQL database

  1. Import the required packages in the main.go file.
package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
)
Copy after login
  1. Establish a connection to the MySQL database in the main function.
func main() {
    db, err := sql.Open("mysql", "root:password@tcp(localhost:3306)/log?charset=utf8")
    if err != nil {
        panic(err.Error())
    }
    defer db.Close()
  
    err = db.Ping()
    if err != nil {
        panic(err.Error())
    }
  
    fmt.Println("Successfully connected to MySQL database")
    // 后续代码将在此处编写
}
Copy after login

Here we use two packages database/sql and github.com/go-sql-driver/mysql. The former is built-in in Go language Database interface, the latter is a MySQL database driver.

4. Create a log table

  1. Create a table named logs in the MySQL database.
CREATE TABLE logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    level VARCHAR(10) NOT NULL,
    message VARCHAR(255) NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
Copy after login
  1. Execute a SQL statement in the main function to create a log table.
func main() {
    // 数据库连接代码...

    _, err = db.Exec(`CREATE TABLE IF NOT EXISTS logs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        level VARCHAR(10) NOT NULL,
        message VARCHAR(255) NOT NULL,
        created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
    )`)
    if err != nil {
        panic(err.Error())
    }

    fmt.Println("Successfully created logs table")
    // 后续代码将在此处编写
}
Copy after login

5. Implement log writing and query functions

  1. Implement the function of writing logs.
func insertLog(db *sql.DB, level string, message string) error {
    _, err := db.Exec(`INSERT INTO logs (level, message) VALUES (?, ?)`, level, message)
    return err
}
Copy after login
  1. Implement the function of querying the log.
func queryLogs(db *sql.DB) ([]Log, error) {
    rows, err := db.Query(`SELECT * FROM logs ORDER BY created_at DESC`)
    if err != nil {
        return nil, err
    }
  
    defer rows.Close()
  
    logs := []Log{}
    for rows.Next() {
        var log Log
        err := rows.Scan(&log.ID, &log.Level, &log.Message, &log.CreatedAt)
        if err != nil {
            return nil, err
        }
      
        logs = append(logs, log)
    }
  
    return logs, nil
}

type Log struct {
    ID        int
    Level     string
    Message   string
    CreatedAt time.Time
}
Copy after login
  1. Call the functions for inserting logs and querying logs in the main function.
func main() {
    // 数据库连接代码与创建日志表代码...
  
    err = insertLog(db, "INFO", "This is an info message")
    if err != nil {
        panic(err.Error())
    }
  
    logs, err := queryLogs(db)
    if err != nil {
        panic(err.Error())
    }
  
    for _, log := range logs {
        fmt.Printf("ID: %d, Level: %s, Message: %s, CreatedAt: %s
", log.ID, log.Level, log.Message, log.CreatedAt)
    }
}
Copy after login

6. Summary
Through the introduction of this article, you have learned how to use MySQL and Go language to develop a simple log management system. We prepared the development environment, connected the MySQL database, created the log table, and implemented the log writing and query functions. I hope this article can provide some reference or help for you to develop a log management system in actual projects.

The above is the detailed content of How to develop a simple log management system using MySQL and Go language. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!