Stop using tail -f (mostly)
brianstorti.com
brianstorti.com
With less, you have to keep track of the current position by timestamp or other unique message, and it's easy to lose your place when the output starts streaming in. With tail, you only need a moment to mark your spot and then it's visually distinct even as more message come in.
This trick doesn't work if your log file has a bunch of identical lines and you want to keep an eye on their rate, though.
That's why suggestions of either named-marks or back-searches aren't considered equally-attractive alternatives to marking the scrollback with a batch of <return>s.
Enter method:
1. Press enter a bunch of times
2. Reload browser
3. Press enter a bunch of times and scroll up
Your method: 1. Search for last line in output to highlight it?
2. Reload page
3. Try and figure out where stuff starts and ends with loads of visual noiseBut the original poster posted a useful tip, and is now getting aggressive downvotes and comments like "This has nothing to do with what is being discussed in this subthread." I think that's unwarranted.
1. ma
2. Reload browser
3. 'a
less method with two marks: 1. ma
2. Reload browser
3. mb
4. 'a * page forward and backward, including using numeric prefixes to indicate a lineno or indicate "repeat 'n' times".
* launch vi if less(1) is working on a file (versus (eg) stdout of some process)
* search fwd/backward
* start examining a new file w/o leaving less(1)
* ...As a junior programmer I got chewed out by my IT department because I was examining a (production) log file in vi. The sysadmin told me I should use less (actually more---this was on Solaris in ~2001). To this day I only read log files with less, but I've never figured out his objection. Negatives to using vi I can imagine are:
- I might write to the log file. That seems like a real worry, although I could also say `vi -R` to prevent it.
- Starving the production system of memory. I'm pretty sure he expressed this concern. Any insight into whether it is legit? Is less actually any better?
Obviously you really should have a log shipping & aggregation service so you can read logs offline, etc, but not every project is large enough for that, nor every org organized enough. So for the sake of argument my premise is, "Assuming you want to read a log on production . . ."
1) for user: less chance (pun intended) to actually change the file when all you wanted was to read it
2) for sysadmin: if sysadmin sees "less somefile.log" in bash history, he knows the user just read the log. If he sees "vi somefile.log" then he doesn't know if the user has also changed the log file (maybe not even knowing it).
The assumption is that you deal with non-malicious users who just make mistakes (which is often the case).
for sysadmin: if sysadmin sees "less somefile.log" in bash history, he knows the user just read the log. If he sees "vi somefile.log" then he doesn't know if the user has also changed the log file (maybe not even knowing it).
In case you didn't know, you can invoke an editor from within less by pressing 'v'. And that wouldn't get registered in the shell history ;)Besides — vim really shouldn't be used on log files. It's editor, not viewer.
I think the two concerns I stated are probably legit, but this one is boring to me. Vim is nicer than less for reading files. I have more navigation commands. I can yank part of the file and save it somewhere else. I can pipe a range of lines through awk/etc. I can switch between files. I can split my screen. Etc. Some of these are probably available in less too (more than more(1) supported in 2001), but I doubt all, and I already know the commands in vim. I'm interested in not clobbering my logs and not crashing the server, but if you tell me vim is an editor not a viewer, I'll ask Why?
Btw re-reading my words I don't mean to sound combative. But the point of my original question was to understand. I've been cargo-culting "use less for logs" for 14 years already.
No, vim also only keeps part of the file loaded, however it will try to count how many lines the file has.
Sometimes I want a viewer to just be a viewer.
Speaking of which: are there any Linux/Unix viewers that do have generalized syntax highlighting support?
Frequently, frequently I am in the position that I need to manipulate an overly-verbose log file to condense out the information I want. I could spend a half hour concocting wizard-like shell invocations, OR I could do it interactively in five minutes with vi...
[0] http://vimdoc.sourceforge.net/htmldoc/starting.html#view
readlink /usr/bin/view
exI think the problem was that the memory and processor were already getting stomped on (thus the need to look at the logs) and vim tried to do a lot of fancy stuffs to get more info on the file as a whole.
I'm generally in the habit of using `view` to do read-only vim. `less` works as well.
http://seclists.org/fulldisclosure/2014/Nov/74
Now I mostly use vi.
Beyond that, I would probably correct a junior employee as well. Even if there's nothing wrong with it, it's not the right tool for the job. When I first started I got 'yelled' at for checking to see if a machine was on the network using tracert instead of ping. It works, but it's not the right tool for the job.
You should download the log file and view it locally. You should never run ad hoc commands on a live production sytem.
And there is no reason that you should have edit privileges on the log file anyway.
Display only lines which match the pattern; lines which do not match the pattern are not displayed. If pattern is empty (if you type & immediately followed by ENTER), any filtering is turned off, and all lines are displayed. While filtering is in effect, an ampersand is displayed at the beginning of the prompt, as a reminder that some lines in the file may be hidden.
yank 10 lines, open a new file, paste the 10 lines, save the file.
Is that possible? My Googling last week didn't find a good solution.
$ less /var/log/msgs
/pjungwlr^M
^G (note line informational line numbers)
v (launch vi)
[double check your line #s, etc]
:d1,. (delete from 1st line, to current line)
10j (go down 10 lines)
:d,$ (delete to EOF)
:w my_newfile
:qhttp://stackoverflow.com/questions/17908555/printing-with-se...
(Actually, there's probably more than one despite their really good duplication grooming, but this was the first hit.)
--retry
keep trying to open a file even if it is inaccessible when tail
starts or if it becomes inaccessible later; useful when follow-
ing by name, i.e., with --follow=name
-F same as --follow=name --retry Do not stop when end-of-file is reached, but rather to wait for
additional data to be appended to the input. If the file is re-
placed (i.e., the inode number changes), tail will reopen the
file and continue. If the file is truncated, tail will reset its
position to the beginning. This makes tail more useful for
watching log files that may get rotated. The -f option is ig-
nored if the standard input is a pipe, but not if it is a FIFO.
So, no -F or --retry but a different default behavior "For f***** sake! I should have used '-F'! Arghhh...!"
Obviously, I'm paraphrasing ;^)> FreeBSD has this
OpenBSD ≠ FreeBSD, and that's fine.
And, since we're being pedantic, when I said “vast majority of the software world”, that includes the OpenBSD project:
“Sending in bug reports
If possible, use the sendbug(1) command to get the bug into our tracking system. Sendbug requires that your system can properly send Internet email. If you cannot use sendbug on a functional OpenBSD machine, please send your bug report to bugs@openbsd.org.
Perhaps what you are sending in is a feature request, not necessarily a bug. New features are accepted, especially with code that implements your suggested new feature.”
I'm not being "pedantic", I just don't think there is anything to change.
Also, if you are using a proper ssh client, opening a second ssh connection to manage the reacting to the log files is habit for me at this point. The only time I'm using tail -F is after a new configuration deployment. Otherwise, I'm looking at archival data in ELK.
Thank you for the suggestion tho. :)
The downside: less buffers and tail -f prints directly. On a slow printing log this can cause events to show up slowly, and can cause performance issues on a fast moving log. If you're piping through a script for processing, tail -f is still the best bet. If you need multiple files, multitail is probably better. less +F hits a quick+easy operational niche and is available almost everywhere (whereas multitail is not).
[1] Everything i've used on Linux in the last few years, not the vanilla one on the Mac, but the one in Homebrew
$ less ./somefile
/somesearch^M (<--- does a search)
F (<--- puts less(1) in "follow mode", highlighting your previous search-term if it occurs in the future)
(Edit: formatting)I typically read logfiles with less +F, but it would be nice to create an alias for patterns in specific types of logs, so I don't have to remember them or rely on command history.
* Note that I needed to "quote" (^V^M) that carriage-return to get the search pattern to work.
Happy searching-and-following.
From creating vi (nvi, on NetBSD) macros, I'm used to thinking in terms of competely replicating the keystrokes that one would do interactively... so I tried it both ways (with and without ^M). The way I published is the one that works. Why the ^M ? Because if you're working interactively the search-pattern isn't submitted until you press Enter. nvi(1) (what NetBSD (and Free and OpenBSD) uses) will accept "-c" "command" arguments which are similar to the less(1) "+"... so, you can:
$ vi -c 123 ./myfile
and start editing "./myfile" at line 123. Nice for edit/compile/edit/compile dance that might happen if you're developing software. Play with that (and try your imagination with other ideas).
Have fun, happy exploring.
I've commented a bit more on them (in the context of other RSS tools) here:
https://www.reddit.com/r/dredmorbius/comments/1udv6i/further...
Folkert's site: http://www.vanheusden.com/ http://www.vanheusden.com/multitail/ http://www.vanheusden.com/rsstail/
Though not quite applicable to logfiles, I've written a script to tail my Newsbeuter feed URLs with Multitail support, for a console / terminal-based RSS feed.
tail -f whatever.log | grep --color=auto -C99 exception
And there are other ways pausing/scrolling back, such as tmux's scroll mode.
There's also no need to do that if you're running tmux, screen or have navigation tools baked into your terminal emulator.
Not that I'm trying to dismiss the effectiveness for +F for those inclined, but as the author acknowledged, +F also comes with some usability issues that -f does not (namely working with multiple files, and piping output into grep et al). Plus learning to navigate though terminal history is a useful skill to have in other situations anyway, and utilities like tmux are actually a very handy tool to use for a whole plethora of additional reasons too.
So kudos to the author for his recommendation and providing helpful write ups to future sysadmins, but I'm inclined disagree with him and instead recommend people stick with -f and learn tmux instead.
tail -n 2000 -f
The beauty of this is a file with less that 2000 files will be read in it's entirety, and you're gracefully managing larger files by cropping out the surplus data at the beginning.And the best thing about this method is you can still pipe grep (which you couldn't do with less) so if you are writing out ~2000 lines rapidly enough that the content you want wouldn't be at the bottom, you can manage the text stream more efficiently (ie grep -v out stuff you don't want or only grep in the content you do want)
I should add that I am a fan of less on many occasions, but in this instance the piping ability of tail is a deal breaker when working with larger files.
> Not that I'm trying to dismiss the effectiveness for +F for those inclined
> kudos to the author for his recommendation and providing helpful write ups to future sysadmins
The ironic thing is, you've been far more dismissive about other peoples suggestions than I had of the author's. As you said yourself, there are a lot different ways this can be done, so why limit us to discussing only one possible solution?
apt-get install tmuxI still like tmux for getting several servers in debug mode on the same screen when using docker though.
= In Your Terminal = Many logging tools, like Splunk, provide great features but are optimized for large-scale deployments. They require installing and configuring servers before they can be effectively used. There is still a need for a robust log file analyzer for the terminal.
= Easy to Use = Just point lnav to a directory and it will take care of the rest. File formats are automatically detected and compressed files are unpacked on the fly.
= Improved Presentation = Log files are a wealth of information, lnav can help highlight the parts that are important and filter out the noise.
# tail -f busy.log
< see something of interest >
ctrl+s # Stops flow of output.
pgup/pgdn for navigation # fn+up/dn for OS X users
ctrl+q # Continues flow.
No need to reinvent the wheel, the functionality you want is probably built into the tools you're already using.Personally, I'd love to see some hot young talent just do a 100% redo of the standard gnu utils from an interface perspective. Just go crazy with new interface and display ideas, novel presentation modes, novel navigation, etc while still maintaining backwards compatibility. I could see a big disruption here.
For example: tail -F somefile.log|ccze -A
For your shell, there's a lot of funky colorful interactive customizations you can get on zsh and fishfish.
The use case that drove its development was needing to keep track of UUIDs across multiple logs - and grep --color will colorize its matches, but not differentiate between ones that have different content. With this, I could watch both logs as data was passed from one to the other and keep track of e.g. the orange one.
I also thought it would be nice to be able to use patterns from logstash's grok, so I wrote grokpat[2] to find patterns for me. A lot of grok's patterns use atomic groups, which aren't available in Python 2, so I wrote redi[3] to convert them from grok's syntax to Python compatible syntax.
So I can now colorize logs easily as follows:
tail -F program.log | synesthesia "$(redi "$(grokpat uuid)")"
[1] https://github.com/cromo/synesthesia
[2] https://github.com/cromo/grokpat
[3] https://github.com/cromo/redi function hl() {
local R=''
while [ $# -gt 0 ]; do
R="$R|$1"
shift
done
env GREP_COLORS="mt=38;5;$((RANDOM%256))" egrep --color=always $R
}
thanksOf course, I'm not opposed to colours, I'm opposed to colours that look tacky / l33t hax0r, which would be most terminal stuff. I like 𝐛𝐨𝐥𝐝 better than trying to find colours I won't hate.
But really, it's 2015. Are you really using a terminal emulator without a buffer search? Are you not using screen or tmux, both of which can do these things natively, with no external tools? Why? And what is wrong with backgrounding the tail command, running your grep, and then foregrounding the tail command?
If tmux can do that, then I'd consider it reason to switch.
There was also a time when there was a utility called inotail, bridging that gap until tail proper was improved. I very much preferred it over regular tail.
poll(), select() et al don't define "readable" as meaning "a byte of data is available". They define it as "read() will not block".
When you read to the end of a file, read() returns "". This is the same as when you try to read from a closed socket. Conceptually, they are linking the concepts of "EOF" and "closed", not the concepts of "EOF" and "waiting for data". And indeed, if you call poll() on a socket that has been closed on the remote end, you will find it is "readable".
Ultimately, regular files just were never intended to be used as pipes. The abstractions just weren't chosen to work in that way.
If that were true, poll() wouldn't return read-ready on a file-based fd until the data was actually sitting in buffers. After all, that's the only way to guarantee it won't block. That would actually be a useful semantic.
But what actually happens is that poll() on a file-based fd is basically a no-op that always returns true immediately, AFAIK. Someone could pull the disk drive cable before you actually call read(), in which case read() will indeed block, forever.
The existing semantic is useless. What argument is there in favor of a useless semantic?
This semantic wouldn't solve the "tail -f" problem, but at least it would be useful: http://cr.yp.to/unix/asyncdisk.html
All this in my humble opinion. less is useful and I may use F to wait for data if I was looking for something in old logs, but for new data I still like tail -f :)
tail -f /var/log/x.log | grep foo -A 20 -B 20
Most of the time.
This is the reason I always share how I do it in hn! LOL
A much nicer alternative, IMHO.
Many of the comments I see on here about using '-F' with tail instead of '-f', live searching, and so on are handled in lnav by default. I would really encourage folks to give it a try.
Yes, this is mentioned in the post, but I feel it is so big it would have deserved large, bold letters.
journalctl -u service-name -f
-f, --follow
Show only the most recent journal entries, and continuously print new entries as they are appended to the journal. journalctl -fu service-nameI always preferred
watch -n 1 -d 'tail /path/to/log/file'
to tail -fbecause of its nice highlighting feature.
My method is usually '+G' to go to the end of the log file and check the damage report. Quick reverse search with '?' + search term to find last error, then probably hit 'n' to find the next previous any other occurrences to determine how frequent it's popping up. If it looks like it's a recurring problem i'll '+F' to see follow latest output. Then CTRL+c to quit that mode.
tail -f still has it's uses for cases as pimlottc mentioned. I like to put a bit of distance between the last bit of output. Especially if its a particularly repetitive and lengthy stacktrace.
Textbook HN hit.
There is also the command `tailf` which is quite similar to 'tail -f'.
2 characters make so much difference :)
I saved you three more!
Maximum savings!
When you jump to the end of the file ('>' command) you'll see "Calculating line numbers... (interrupt to abort)" and interrupt (ctrl-C) here will also turn them off.
Of course I'll probably fail to use any of it because of finger memory just typing out tail -f for me.
Meanwhile, tail -f still useful for simple tailing to multiple machine, like
function dogfight_tail {
logfile=/var/log/nginx/access.log
pids=""
for box in 02 03; do
ssh lb$box tail -f $logfile | grep " 500 " & # find error machines
pids="$pids $!"
done
trap 'kill -9 $pids' SIGINT
trap wait
}
dogfight_tailtail -f sys.log | grep NETDEV
But I would definitely give this a try, thanks for sharing.
$ alias stalk='less +F'"What is a linux command that's mostly not known?".
I could not remember anything that's special, at least for me at the time but "less -F" poped up to my mind. Thank you :)
Oh now I can think of ccze, column and tac. Interviews..
ctrl+c...
<shit its not working>
ctrl+c * 1e9 impatiently
...
build stopped
oops
You can also open the file and engage auto-revert-mode or auto-revert-mode-tail. In my status bar it shows up as ARev mode.
Also you can bind those to your auto-mode-alist so all .log files get the tail treatment or whatever.
Scrolling can get weird.
Theres some google-able settings for the timeout to revert, default is about a sip of water (a few seconds?) but I guess you could crank it down to 1 second or something.
I like doing this in emacs so its all in the same ecosystem, if I need to cut and paste something weird to test it or put the message into code or even more likely to cut and paste actual error messages into docs or comments, I can do it inside emacs.
what is meant by 'pretty much?'
Interprets color codes as RAW, relaying them to the screen as-is.
/thefox