hunting/utils/Log/src/Log.cpp
2023-09-24 16:16:15 -07:00

101 lines
2.6 KiB
C++

/*
* Copyright (c) 2023 Fancy Code.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Log.h"
#include "ILogCpp.h"
#include <stdarg.h>
#include <stdio.h>
#include <iostream>
#include <memory>
#include <string.h>
static void LogFree(ILog *object)
{
printf("log instance free.\n");
if (object)
{
free(object);
}
}
static int LogPrintf(ILog *object, const char *function, const int line, const enum LogType type, const char *format, ...)
{
// TODO:
// LogTypeToString(type);
constexpr int SEND_TRACE_BUFF_SIZE = 2048;
char buff[SEND_TRACE_BUFF_SIZE] = {0};
snprintf(buff, SEND_TRACE_BUFF_SIZE, "[%s:%d]:", function, line);
// ILog::GetInstance()->Log(buff);
const int headLen = strlen(buff);
va_list vargs;
va_start(vargs, format);
int len = vsnprintf(buff + headLen, SEND_TRACE_BUFF_SIZE - headLen, format, vargs);
va_end(vargs);
switch (type)
{
case LOG_TYPE_INFORMATION:
ILogCpp::GetInstance()->InFo(buff);
break;
case LOG_TYPE_WARNING:
ILogCpp::GetInstance()->Warning(buff);
break;
case LOG_TYPE_ERROR:
ILogCpp::GetInstance()->Error(buff);
break;
case LOG_TYPE_DEBUG:
ILogCpp::GetInstance()->Debug(buff);
break;
case LOG_TYPE_TRACE:
ILogCpp::GetInstance()->Trace(buff);
break;
default:
break;
}
return len;
}
static void LogImplInit(Log *log)
{
printf("LogImplInit\n");
((ILog *)log)->printf = LogPrintf;
((ILog *)log)->free = LogFree;
}
void NewLog(Log **log)
{
if (!log)
{
printf("STATUS_CODE_INVALID_PARAMENTER\n");
return;
}
if (!(*log))
{
*log = (Log *)malloc(sizeof(Log));
if (*log)
{
printf("NewLog succeed.\n");
NewILog((ILog **)log);
LogImplInit(*log);
return;
}
LogError("NewLog failed.\n");
return;
}
// else
{
LogImplInit(*log);
return;
}
}