增加log文件存取,以及增加LOG函数

This commit is contained in:
hoteas 2020-02-22 00:13:41 +08:00
parent ab294ca6f0
commit bb2311148e
10 changed files with 148 additions and 123 deletions

View File

@ -1,7 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="b2aca021-ff30-4cbf-8dc9-8cdd4f4c39dc" name="Default Changelist" comment="" />
<list default="true" id="b2aca021-ff30-4cbf-8dc9-8cdd4f4c39dc" name="Default Changelist" comment="优化初步使用">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/application.go" beforeDir="false" afterPath="$PROJECT_DIR$/application.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/const.go" beforeDir="false" afterPath="$PROJECT_DIR$/const.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/context.go" beforeDir="false" afterPath="$PROJECT_DIR$/context.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/error.go" beforeDir="false" afterPath="$PROJECT_DIR$/error.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/example/config/config.json" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/example/config/confignote.json" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/example/main.go" beforeDir="false" afterPath="$PROJECT_DIR$/example/main.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/func.go" beforeDir="false" afterPath="$PROJECT_DIR$/func.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/var.go" beforeDir="false" afterPath="$PROJECT_DIR$/var.go" afterDir="false" />
</list>
<option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
@ -76,6 +87,10 @@
<workItem from="1573372583551" duration="5522000" />
<workItem from="1582172338195" duration="5196000" />
<workItem from="1582181939594" duration="501000" />
<workItem from="1582182581675" duration="242000" />
<workItem from="1582182838832" duration="14000" />
<workItem from="1582292274571" duration="542000" />
<workItem from="1582294370646" duration="7170000" />
</task>
<task id="LOCAL-00001" summary="清理">
<created>1573372845218</created>
@ -133,7 +148,21 @@
<option name="project" value="LOCAL" />
<updated>1582182399676</updated>
</task>
<option name="localTasksCounter" value="9" />
<task id="LOCAL-00009" summary="增加访问ip打印等功能">
<created>1582182736196</created>
<option name="number" value="00009" />
<option name="presentableId" value="LOCAL-00009" />
<option name="project" value="LOCAL" />
<updated>1582182736196</updated>
</task>
<task id="LOCAL-00010" summary="优化初步使用">
<created>1582292694027</created>
<option name="number" value="00010" />
<option name="presentableId" value="LOCAL-00010" />
<option name="project" value="LOCAL" />
<updated>1582292694027</updated>
</task>
<option name="localTasksCounter" value="11" />
<servers />
</component>
<component name="TypeScriptGeneratedFilesManager">
@ -158,6 +187,18 @@
<MESSAGE value="数据库缓存" />
<MESSAGE value="增加跨域配置,以及增加配置说明" />
<MESSAGE value="增加访问ip打印等功能" />
<option name="LAST_COMMIT_MESSAGE" value="增加访问ip打印等功能" />
<MESSAGE value="优化初步使用" />
<option name="LAST_COMMIT_MESSAGE" value="优化初步使用" />
</component>
<component name="XDebuggerManager">
<breakpoint-manager>
<breakpoints>
<line-breakpoint enabled="true" type="DlvLineBreakpoint">
<url>file://$PROJECT_DIR$/func.go</url>
<line>49</line>
<option name="timeStamp" value="1" />
</line-breakpoint>
</breakpoints>
</breakpoint-manager>
</component>
</project>

View File

@ -4,17 +4,13 @@ import (
"bytes"
"database/sql"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
type Application struct {
@ -106,8 +102,9 @@ func (this *Application) Run(router Router) {
//异常处理
defer func() {
if err := recover(); err != nil {
this.SetError(errors.New(fmt.Sprint(err)), LOG_FMT)
//log.Println(err)
//this.SetError(errors.New(fmt.Sprint(err)), LOG_FMT)
logFmt(err, 2, LOG_ERROR)
this.Run(router)
}
}()
@ -126,7 +123,7 @@ func (this *Application) Run(router Router) {
//启动服务
this.Server.Addr = ":" + this.Port
err := this.Server.ListenAndServe()
log.Println(err)
logFmt(err, 2)
ch <- 1
}()
@ -138,19 +135,19 @@ func (this *Application) Run(router Router) {
//启动服务
this.Server.Addr = ":" + this.TLSPort
err := this.Server.ListenAndServeTLS(this.Config.GetString("tlsCert"), this.Config.GetString("tlsKey"))
log.Println(err)
logFmt(err, 2)
ch <- 2
}()
} else {
log.Println("没有端口启用")
logFmt("没有端口启用", 2, LOG_INFO)
return
}
value := <-ch
log.Println("启动服务失败 : ", value)
logFmt("启动服务失败 : "+ObjToStr(value), 2, LOG_ERROR)
}
//启动实例
@ -217,11 +214,11 @@ func (this *Application) SetConfig(configPath ...string) {
cmap.JsonToMap(string(btes), &this.Error)
for k, v := range cmap {
this.Config.Put(k, v) //程序配置
Config.Put(k, v) //系统配置
this.Config[k] = v //程序配置
Config[k] = v //系统配置
}
} else {
log.Println("配置文件不存在,或者配置出错,使用缺省默认配置")
logFmt("配置文件不存在,或者配置出错,使用缺省默认配置", 2)
}
@ -238,24 +235,16 @@ func (this *Application) SetConfig(configPath ...string) {
//写入配置说明
var configNoteByte bytes.Buffer
json.Indent(&configNoteByte, []byte(ConfigNote.ToJsonString()), "", "\t")
ioutil.WriteFile(filepath.Dir(this.configPath)+"/confignote.json", configNoteByte.Bytes(), os.ModeAppend)
//写入配置
err = ioutil.WriteFile(this.configPath, configByte.Bytes(), os.ModeAppend)
if err != nil {
os.MkdirAll(filepath.Dir(this.configPath), os.ModeDir)
os.Create(this.configPath)
err = ioutil.WriteFile(this.configPath, configByte.Bytes(), os.ModeAppend)
if err != nil {
this.Error.SetError(err)
}
//写入配置说明
os.Create(filepath.Dir(this.configPath) + "/confignote.json")
ioutil.WriteFile(filepath.Dir(this.configPath)+"/confignote.json", configNoteByte.Bytes(), os.ModeAppend)
}
}
}
//连接判断,返回true继续传输至控制层false则停止传输
@ -338,7 +327,7 @@ func (this *Application) handler(w http.ResponseWriter, req *http.Request) {
this.crossDomain(&context)
//是否展示日志
if this.Config.GetInt("connectLogShow") != 0 {
log.Println(context.HandlerStr + time.Now().Format(" 2006-01-02 15:04 ") + Substr(context.Req.RemoteAddr, 0, strings.Index(context.Req.RemoteAddr, ":")))
logFmt(Substr(context.Req.RemoteAddr, 0, strings.Index(context.Req.RemoteAddr, ":"))+" "+context.HandlerStr, 0, LOG_INFO)
}
//访问拦截true继续false暂停

View File

@ -1,9 +1,15 @@
package hotime
type LOG_MODE int
const (
LOG_FMT = 0
LOG_NIL = 1
LOG_FILE = 2
LOG_NIL = 0
LOG_FMT = 1
//LOG_FILE = 2
LOG_INFO LOG_MODE = 0
LOG_WARN LOG_MODE = 1
LOG_ERROR LOG_MODE = 2
)
//session储存头

View File

@ -37,7 +37,7 @@ func (this *Context) Display(statu int, data interface{}) {
tpe := this.Config.GetMap("error").GetString(ObjToStr(statu))
if tpe == "" {
this.SetError(errors.New("找不到对应的错误码"))
logFmt(errors.New("找不到对应的错误码"), 2, LOG_WARN)
}
temp["type"] = tpe

View File

@ -1,40 +1,25 @@
package hotime
import (
"log"
)
//框架层处理错误
type Error struct {
error
err error
}
func (this *Error) GetError() error {
return this.err
return this.error
}
func (this *Error) SetError(err error, loglevel ...int) {
this.err = nil
this.error = nil
if err == nil {
this.error = err
this.err = err
return
}
lev := Config.GetInt("logLevel")
if len(loglevel) != 0 {
lev = loglevel[0]
}
if lev == LOG_FMT {
log.Println(err)
}
if lev == LOG_FILE {
log.Println(err)
}
this.err = err
this.error = err
return
}

View File

@ -1,30 +0,0 @@
{
"cacheLongTime": 2592000,
"cacheShortTime": 7200,
"dbCached": 0,
"dbHost": "127.0.0.1",
"dbName": "test",
"dbPort": "3306",
"dbPwd": "root",
"dbUser": "root",
"debug": 1,
"defFile": [
"index.html",
"index.htm"
],
"error": {
"1": "内部系统异常",
"2": "访问权限异常",
"3": "请求参数异常",
"4": "数据处理异常",
"5": "数据结果异常"
},
"logLevel": 1,
"modeRouterStrict": false,
"port": "0",
"sessionName": "HOTIME",
"tlsCert": "",
"tlsKey": "",
"tlsPort": "0",
"tpt": "tpt"
}

View File

@ -1,34 +0,0 @@
{
"cacheLongTime": "两级缓存长缓存存储时间60 * 60 * 24 * 30一般为数据库或者redis缓存",
"cacheShortTime": "两级缓存短缓存存储时间60 * 60 * 2一般为内存缓存",
"connectLogShow": "如果需要web访问链接、访问ip、访问时间打印0为关闭其他数字开启此功能",
"crossDomain": "如果需要跨域设置,空字符串为不开启,*为开启所有网站允许跨域http://www.baidu.com为指定域允许跨域",
"dbCached": "是否开启数据库缓存0为关闭其他开启",
"dbHost": "数据库ip地址默认127.0.0.1",
"dbName": "数据库名称sqlite为文件路径比如a/x.db",
"dbPort": "数据库端口",
"dbPwd": "数据库密码",
"dbType": "如果需要使用自动数据库配置请设置此项手动配置数据库不需要目前支持mysqlsqlite",
"dbUser": "数据库用户名",
"debug": "是否开启debug模式0关闭其他开启debug模式下日志展示更全",
"defFile": "默认访问文件默认访问index.html或者index.htm文件",
"error": {
"1": "内部系统异常,在环境配置,文件访问权限等基础运行环境条件不足造成严重错误时使用",
"2": "访问权限异常,没有登录或者登录异常等时候使用",
"3": "请求参数异常request参数不满足要求比如参数不足参数类型错误参数不满足要求等时候使用",
"4": "数据处理异常,数据库操作或者三方请求返回的结果非正常结果,比如数据库突然中断等时候使用",
"5": "数据结果异常一般用于无法给出response要求的格式要求下使用比如response需要的是string格式但你只能提供int数据时",
"注释": "web服务内置错误提示自定义异常建议10开始"
},
"logLevel": "日志等级0打印1关闭2记录到文件",
"modeRouterStrict": "路由严格模式false,为大小写忽略必须匹配true必须大小写匹配",
"port": "web服务开启Http端口0为不启用http服务",
"redisHost": "如果需要使用redis服务时配置默认服务ip127.0.0.1",
"redisPort": "如果需要使用redis服务时配置默认服务端口6379",
"redisPwd": "如果需要使用redis服务时配置默认服务密码123456",
"sessionName": "设置session的cookie名默认HOTIME",
"tlsCert": "https证书",
"tlsKey": "https密钥",
"tlsPort": "web服务https端口0为不启用https服务",
"tpt": "静态文件目录默认为程序目录下tpt目录"
}

View File

@ -4,7 +4,6 @@ import (
"code.hoteas.com/hoteas/hotime"
"code.hoteas.com/hoteas/hotime/tools/db"
"fmt"
"strings"
//"go.hoteas.com/hotime/cache"
"golang.org/x/net/websocket"
"time"
@ -16,7 +15,7 @@ func main() {
appIns := hotime.Application{}
appIns.SetConnectListener(func(context *hotime.Context) bool {
fmt.Println(context.HandlerStr + time.Now().Format(" 2006-01-02 15:04 ") + hotime.Substr(context.Req.RemoteAddr, 0, strings.Index(context.Req.RemoteAddr, ":")))
//fmt.Println(context.HandlerStr + time.Now().Format(" 2006-01-02 15:04 ") + hotime.Substr(context.Req.RemoteAddr, 0, strings.Index(context.Req.RemoteAddr, ":")))
//this.HandlerStr = "/test.html"
return true

68
func.go
View File

@ -3,8 +3,13 @@ package hotime
import (
"crypto/md5"
"encoding/hex"
"fmt"
"math"
"os"
"path/filepath"
"runtime"
"strings"
"time"
)
//安全锁
@ -24,6 +29,69 @@ import (
// return res
//}
func LogFmt(logMsg interface{}, loglevel ...LOG_MODE) {
logFmt(logMsg, 2, loglevel...)
}
//日志打印以及存储到文件
func logFmt(logMsg interface{}, printLevel int, loglevel ...LOG_MODE) {
if Config.GetInt("logLevel") == int(LOG_NIL) {
return
}
lev := LOG_INFO
if len(loglevel) != 0 {
lev = loglevel[0]
}
gofile := ""
if Config.GetInt("debug") != 0 && printLevel != 0 {
_, file, line, ok := runtime.Caller(printLevel)
if ok {
gofile = " " + file + ":" + ObjToStr(line)
}
}
logStr := ""
if lev == LOG_INFO {
logStr = "info:"
}
if printLevel == 0 {
logStr = "connect:"
}
if lev == LOG_WARN {
logStr = "warn:"
}
if lev == LOG_ERROR {
logStr = "error:"
}
logStr = fmt.Sprintln(time.Now().Format("2006/01/02 15:04:05"), logStr, logMsg, gofile)
//打印日志
fmt.Print(logStr)
//不需要存储到文件
if Config.GetString("logFile") == "" {
return
}
//存储到文件
logFilePath := time.Now().Format(Config.GetString("logFile"))
os.MkdirAll(filepath.Dir(logFilePath), os.ModeAppend)
//os.Create(logFilePath)
f, err := os.OpenFile(logFilePath, os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
return
}
f.Write([]byte(logStr))
f.Close()
}
//字符串首字符大写
func StrFirstToUpper(str string) string {
if len(str) == 0 {

9
var.go
View File

@ -7,7 +7,7 @@ var App = map[string]*Application{} //整个项目
var Config = Map{
"debug": 1, //debug 0关闭1开启
"logLevel": LOG_NIL,
"logLevel": LOG_FMT,
"dbHost": "127.0.0.1",
"dbName": "test",
"dbUser": "root",
@ -26,7 +26,7 @@ var Config = Map{
"tpt": "tpt",
"defFile": []string{"index.html", "index.htm"},
"modeRouterStrict": false, //路由严格模式/a/b/c
"port": "0",
"port": "80",
"sessionName": "HOTIME",
"tlsPort": "0",
"tlsKey": "",
@ -34,7 +34,8 @@ var Config = Map{
}
var ConfigNote = Map{
"logLevel": "日志等级0打印1关闭2记录到文件",
"logLevel": "日志等级0关闭1打印",
"logFile": "如果需要存储日志文件时使用,保存格式为:a/b/c/20060102150405.txt,将生成a/b/c/年月日时分秒.txt按需设置",
"debug": "是否开启debug模式0关闭其他开启debug模式下日志展示更全", //debug 0关闭1开启
"dbHost": "数据库ip地址默认127.0.0.1",
"dbName": "数据库名称sqlite为文件路径比如a/x.db",
@ -62,7 +63,7 @@ var ConfigNote = Map{
"modeRouterStrict": "路由严格模式false,为大小写忽略必须匹配true必须大小写匹配", //路由严格模式/a/b/c
"connectLogShow": "如果需要web访问链接、访问ip、访问时间打印0为关闭其他数字开启此功能",
"sessionName": "设置session的cookie名默认HOTIME",
"port": "web服务开启Http端口0为不启用http服务",
"port": "web服务开启Http端口0为不启用http服务,默认80",
"tlsPort": "web服务https端口0为不启用https服务",
"tlsKey": "https密钥",
"tlsCert": "https证书",