file_monitoring/cmd/server.go

74 lines
1.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package cmd
import (
"file_monitoring/config"
"git.hpds.cc/Component/logging"
"github.com/fsnotify/fsnotify"
"github.com/spf13/cobra"
"go.uber.org/zap"
"log"
)
var (
ConfigFile string = "./config/config.yaml"
)
func Run() *cobra.Command {
//创建一个监控对象
watch, err := fsnotify.NewWatcher()
if err != nil {
//log.Fatal(err)
logging.L().Error("new watcher err", zap.Error(err))
}
defer watch.Close()
//添加要监控的对象,文件或文件夹
err = watch.Add(config.DefaultMonitoringDirectory)
if err != nil {
logging.L().Error("new watcher err", zap.Error(err))
}
//我们另启一个goroutine来处理监控对象的事件
go func() {
for {
select {
case ev := <-watch.Events:
{
//判断事件发生的类型如下5种
// Create 创建
// Write 写入
// Remove 删除
// Rename 重命名
// Chmod 修改权限
if ev.Op&fsnotify.Create == fsnotify.Create {
logging.L().Info("创建文件", zap.String("文件名", ev.Name))
//log.Println("创建文件 : ", ev.Name)
}
if ev.Op&fsnotify.Write == fsnotify.Write {
logging.L().Info("写入文件", zap.String("文件名", ev.Name))
//log.Println("写入文件 : ", ev.Name)
}
if ev.Op&fsnotify.Remove == fsnotify.Remove {
logging.L().Info("删除文件", zap.String("文件名", ev.Name))
//log.Println("删除文件 : ", ev.Name)
}
if ev.Op&fsnotify.Rename == fsnotify.Rename {
logging.L().Info("重命名文件", zap.String("文件名", ev.Name))
//log.Println("重命名文件 : ", ev.Name)
}
if ev.Op&fsnotify.Chmod == fsnotify.Chmod {
logging.L().Info("修改权限", zap.String("文件名", ev.Name))
//log.Println("修改权限 : ", ev.Name)
}
}
case err := <-watch.Errors:
{
log.Println("error : ", err)
return
}
}
}
}()
//循环
select {}
}