一个简单的写txt格式Log的方法,支持多线程

using System;
using System.IO;
using System.Web;

public class SimpleLog
{
    #region 写日志,指定文件夹、文件名称、内容
    public static void Write(string logPath, string fileName, string content)
    {
        try
        {
            // 常用的获取服务器目录的方法,但在多线程环境下,会调用失败;
            // string strPath = HttpContext.Current.Server.MapPath(logPah);

            string folderPath = HttpRuntime.AppDomainAppPath + "/log";

            if (logPath.Trim() != "")
            {
                folderPath += "/" + logPath;
            }

            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            folderPath = folderPath + "\\" + fileName + ".txt";

            StreamWriter fs = new StreamWriter(folderPath, true, System.Text.Encoding.UTF8);
            fs.WriteLine(content);
            fs.Close();
        }
        catch(Exception ex)
        { }
    }
    #endregion

    #region 在LOG文件夹根目录下写日志
    public static void Write(string content)
    {
        content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss    ") + content;
        string fileName = DateTime.Today.ToString("yyyyMMdd");
        Write("", fileName, content);
    }
    #endregion

    #region 在特定文件夹写日志
    public static void Write(string folderName, string content)
    {
        string fileName = DateTime.Today.ToString("yyyyMMdd");
        content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss    ") + content;
        Write(folderName, fileName, content);
    }
    #endregion
}


只包含写的方法,用来记录一些简单的内容,更高级的建议还是使用Log4Net这类专业的工具。

调用方法很简单:

SimpleLog.Write("xxx", “要记录的内容”);
或者用异步的方式:

var task = new TaskFactory().StartNew(() =>
            {
                SimpleLog.Write("xxx", "要记录的内容");
            });

会在站点根目录的/log/xxx目录下生成以当前日期命名的文件,如20161005.txt

### 正确传递并验证 JSON 数据 为了确保从前端后端的数据交互安全可靠,在发送请求时应采用合适的 HTTP 方法以及设置正确的 Content-Type 头部。对于 JSON 格式的对象,推荐使用 `POST` 或者 `PUT` 请求方法,并将 `Content-Type` 设置为 `application/json`[^1]。 在 Java Spring Boot 应用程序中,可以利用 `@RequestBody` 注解来绑定来自客户端的 JSON 输入流至指定的方法参数上。此注解会自动调用 Jackson 库或其他配置好的消息转换器来进行反序列化操作,从而简化了复杂类型的映射过程。 #### 验证 JSON 结构的有效性 为了进一步增强系统的健壮性和安全性,建议对接收到的数据实施严格的校验逻辑。这可以通过引入 Hibernate Validator 来实现,它提供了丰富的约束注解用于声明式地定义属性级别的规则: ```java public class User { @NotNull(message = "用户名不能为空") private String username; @Email(message = "邮箱格式不正确") private String email; // getter and setter methods... } ``` 当控制器接收到带有上述类作为入参的 POST 请求时,Spring MVC 会在调用目标 handler 前执行内置的 Validation 过程。如果发现任何违反预设条件的情况,则立即返回相应的错误提示信息给调用方。 此外,还可以自定义全局异常处理器捕获 MethodArgumentNotValidException 类型的异常事件,以便集中管理和定制响应体的内容格式。 ```java @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<Map<String, Object>> handleValidationExceptions( MethodArgumentNotValidException ex) { Map<String, Object> response = new HashMap<>(); List<String> errors = ex.getBindingResult() .getFieldErrors() .stream() .map(DefaultMessageSourceResolvable::getDefaultMessage) .collect(Collectors.toList()); response.put("status", HttpStatus.BAD_REQUEST.value()); response.put("errors", errors); return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); } } ``` 以上措施能够有效保障前后端之间通信的安全稳定,同时也提高了用户体验的质量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值