最后,我通过在当前项目中编写以下代码行解决了我的问题。
public class StoreLogsintoFileShare
{
public static string pathString = string.Empty;
public static void CreateSubFolderAndFile()
{
// Specify a name for your top-level folder.
string currentFolderPath = "/mnt/azure";
string subFolderName = "WebApplication";
string date = DateTime.Now.ToString("ddd MM.dd.yyyy");
string time = DateTime.Now.ToString("HH.mm tt");
string format = "{0} on {1} At {2}.txt";
string fileName = string.Format(format, "Logs", date, time);
// To create a string that specifies the path to a subFolderName under your
// top-level folder, add a name for the subFolderName to folderName.
pathString = System.IO.Path.Combine(currentFolderPath, subFolderName);
//Create the subfolder.
System.IO.Directory.CreateDirectory(pathString);
// Use Combine again to add the file name to the path.
pathString = System.IO.Path.Combine(pathString, fileName);
// Verify the path that you have constructed.
Debug.WriteLine("Path to my file: {0}\n", pathString);
// Check that the file doesn't already exist. If it doesn't exist, create
// the file and write logs in to it.
// DANGER: System.IO.File.Create will overwrite the file if it already exists.
if (!System.IO.File.Exists(pathString))
{
using (System.IO.FileStream fs = System.IO.File.Create(pathString))
{
}
}
else
{
Debug.WriteLine("File \"{0}\" already exists.", fileName);
return;
}
}
}
我在Startup.cs中调用上述方法,这就是为什么每当我启动应用程序时,会立即在名为“WebApplication”的子文件夹下使用“<strong>Logs on Thu 08.30.2018 At 18.43 PM.txt”创建一个新文件已经在 Kubernetes 的一个 pod 上创建/mnt/azure
。
一旦在/mnt/azure
位置的 kuberneres 的 pod 上创建了文件,那么我必须在任何需要的地方编写一些虚拟日志,例如:
await System.IO.File.AppendAllLinesAsync(StoreLogsintoFileShare.pathString, new[] {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),ex.ToString()});
注意:但在上面的代码中,我没有动态获取 pod 名称。我只是使用静态名称作为“WebApplication”来创建子文件夹。