UE4+Log日志

虚幻引擎:4.22

VS:2017

将自定义的Log日志,存放到项目工程或者打包程序的Saved/Logs目录下

1、创建一个C++空类,我命名为GunTestLog

2、GunTestLog.h文件

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"

void UE_GUNTEST_LOG_S(FString FileName, FString Value);

static FORCEINLINE void UE_GUNTEST_LOG(FString FileName, const TCHAR* Format, ...)
{
	TCHAR TempStr[1024];

	va_list Ptr;

	va_start(Ptr, Format);

	FCString::GetVarArgs(TempStr, ARRAY_COUNT(TempStr), ARRAY_COUNT(TempStr) - 1, Format, Ptr);

	va_end(Ptr);

	UE_GUNTEST_LOG_S(FileName, FString(TempStr));
}

3、GunTestLog.cpp文件

// Fill out your copyright notice in the Description page of Project Settings.

#include "GunTestLog.h"
#include "Paths.h"
#include "FileHelper.h"
#include "PlatformFileManager.h"

void UE_GUNTEST_LOG_S(FString _FileName, FString _Value)
{
	static bool mIsNewLog = true;

	FString mSaveDirectory = FPaths::ProjectSavedDir();

	mSaveDirectory.Append("Logs/GunTest/");

	FString mTmpFileName = _FileName;

	mTmpFileName.Append(".log.txt");

	IPlatformFile& mPlatformFile = FPlatformFileManager::Get().GetPlatformFile();

	if (mPlatformFile.DirectoryExists(*mSaveDirectory))
	{
		mPlatformFile.CreateDirectoryTree(*mSaveDirectory);
	}

	//获取Log日志的绝对路径.
	FString mAbsoluteFilePath = mSaveDirectory + "/" + mTmpFileName;

	IFileManager* mFileManager = &IFileManager::Get();

	uint32 WriteFlags = (uint32)(EFileWrite::FILEWRITE_Append);

	//如果Log文件存在,修改名字另存.
	if (mPlatformFile.FileExists(*mAbsoluteFilePath) && mIsNewLog)
	{
		mIsNewLog = false;

		FString AbsoluteDestinationPath = mSaveDirectory + "/" + FDateTime::Now().ToString() + "-" + mTmpFileName;

		mPlatformFile.MoveFile(*AbsoluteDestinationPath, *mAbsoluteFilePath);

		mPlatformFile.DeleteFile(*mAbsoluteFilePath);
	}
	else
	{
		FString TextToSave = FDateTime::Now().ToString();

		TextToSave.Append("-");

		TextToSave.Append(_Value);

		TextToSave.Append("\r\n");

		FFileHelper::SaveStringToFile(TextToSave, *mAbsoluteFilePath, FFileHelper::EEncodingOptions::AutoDetect, mFileManager, WriteFlags);
	}
}

 4、在需要保存日志的.cpp文件中调用

UE4+Log日志_第1张图片

 5、第4步我是为了测试按键信息,然后将按键日志保存到Saved/Logs/GunTest/文件目录下

UE4+Log日志_第2张图片

 

你可能感兴趣的:(UE4,C++,UE4,日志,C++)