How to write log to file
os.Open()
must have worked differently in the past, but this works for me:
f, err := os.OpenFile("testlogfile", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
defer f.Close()
log.SetOutput(f)
log.Println("This is a test log entry")
Based on the Go docs, os.Open()
can't work for log.SetOutput
, because it opens the file "for reading:"
func Open
func Open(name string) (file *File, err error)
Open
opens the named
file for reading. If successful, methods on the returned file can be
used for reading; the associated file descriptor has modeO_RDONLY
. If
there is an error, it will be of type*PathError
.
EDIT
Moved defer f.Close()
to after if err != nil
check
How to write logs in text file when using java.util.logging.Logger
Try this sample. It works for me.
public static void main(String[] args) {
Logger logger = Logger.getLogger("MyLog");
FileHandler fh;
try {
// This block configure the logger with handler and formatter
fh = new FileHandler("C:/temp/test/MyLogFile.log");
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
// the following statement is used to log any messages
logger.info("My first log");
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("Hi How r u?");
}
Produces the output at MyLogFile.log
Apr 2, 2013 9:57:08 AM testing.MyLogger main
INFO: My first log
Apr 2, 2013 9:57:08 AM testing.MyLogger main
INFO: Hi How r u?
Edit:
To remove the console handler, use
logger.setUseParentHandlers(false);
since the ConsoleHandler is registered with the parent logger from which all the loggers derive.
How to write log file in c#?
From the performance point of view your solution is not optimal. Every time you add another log entry with +=, the whole string is copied to another place in memory. I would recommend using StringBuilder instead:
StringBuilder sb = new StringBuilder();
...
sb.Append("log something");
...
// flush every 20 seconds as you do it
File.AppendAllText(filePath+"log.txt", sb.ToString());
sb.Clear();
By the way your timer event is probably executed on another thread. So you may want to use a mutex when accessing your sb
object.
Another thing to consider is what happens to the log entries that were added within the last 20 seconds of the execution. You probably want to flush your string to the file right before the app exits.
Writing iOS application logs on a text file
Okay I got confused and I totally forgot this document is not supposed to show up in the Files.app
. It's stored inside the app's container. If you want to share it from the documents sheet and send it to another device via AirDrop or whatever add this action to trigger when you tap a button intended to share the document.
let fm = FileManager.default
let fileUrl = fm.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("log.txt")
var filesToShare = [Any]()
filesToShare.append(fileUrl)
let activityViewController = UIActivityViewController(activityItems: filesToShare, applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
Android Writing Logs to text File
Hope this can help...
public void appendLog(String text)
{
File logFile = new File("sdcard/log.file");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
How to write to a file, using the logging Python module?
An example of using logging.basicConfig
rather than logging.fileHandler()
logging.basicConfig(filename=logname,
filemode='a',
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%H:%M:%S',
level=logging.DEBUG)
logging.info("Running Urban Planning")
logger = logging.getLogger('urbanGUI')
In order, the five parts do the following:
- set the output file (
filename=logname
) - set it to append rather than overwrite (
filemode='a'
) - determine the format of the output message (
format=...
) - determine the format of the output time (
datefmt='%H:%M:%S'
) - and determine the minimum message level it will accept (
level=logging.DEBUG
).
What are the best practices to write a log file on a web application?
if you are using nodejs then the best option for you is to use bunyan available here: https://www.npmjs.com/package/bunyan
This will do the date format etc.
What to write into log file?
Here are some suggestions for content:
- timestamp
- message
- log message type (such as error, warning, trace, debug)
- thread id ( so you can make sense of the log file from a multi threaded application)
Best practices for implementation:
- Put a mutex around the write method so that you can be sure that each write is thread safe and will make sense.
- Send 1 message at at a time to the log file, and specify the type of log message each time. Then you can set what type of logging you want to take on program startup.
- Use no buffering on the file, or flush often in case there is a program crash.
Edit: I just noticed the question was tagged with Python, so please see S. Lott's answer before mine. It may be enough for your needs.
Related Topics
Symbolicate Crash in iOS8 with Xcode 6 .1
Get Uiwebview Content's Height
How to Create Custom View Programmatically in Swift Having Controls Text Field, Button etc
How to Handle Action Buttons in Push Notifications
Malloc Error "Can't Allocate Region" Failed with Error Code 12. Any Idea How to Resolve This
Playing Video into Uitableview
Programmatically Creating Uilabel
Static Linking with Swift, Xcode6-Beta
Core Location Not Working in iOS 8
Core Data: Delete All Objects of an Entity Type, Ie Clear a Table
Pulling Data from a Cmsamplebuffer in Order to Create a Deep Copy
App Crashing When Using Firebase Auth, Reason: 'Default App Has Already Been Configured.'
Share Video on Twitter with Fabric API Without Composer iOS
How to Check If Haptic Engine (Uifeedbackgenerator) Is Supported