puts doesn't print stuff to console - ruby-on-rails

i'm using POW for local rails development. i don't know why, but i can't print or puts information to my development.log. i want to puts the content of variables to console / log from my controller. any advice?
i read my logs with tail -f logs/development.log
thanks!

Instead of puts, try logger.info(). Logging in Rails is very flexible, but it does mean that you might not be able to use the simplest tools sometimes.

If you're doing debugging and only want to see some messages in the logs you can do the following:
Rails.logger.debug("debug::" + person.name)
and
$ pow logs | grep debug::
now you'll only see logging messages that start with debug::

Another option is to use the rails tagging logger, http://api.rubyonrails.org/classes/ActiveSupport/TaggedLogging.html.
logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
logger.tagged('BCX') { logger.info 'Stuff' } # Logs "[BCX] Stuff"
$ pow logs | grep BCX

For anyone who still can't get it to work, remember that Ruby doesn't use semicolons. They are only used to chain commands. I was adding them at the end due to muscle memory (coming from PHP), so the ruby console thought I was still entering commands:
irb(main):001:0> puts "hi";
irb(main):002:0* puts "hi"
hi
hi
=> nil
Hope this helps someone.

Related

How to redirect output to file if no console detected in Nim

I want my Nim program to write to the console if there is one, and redirect echo to write to a file if there isn't. Is there an equivalent to the Environment.UserInteractive property in .NET which I could use to detect if no console is available and redirect stdout in that case?
It's a combination of using isatty() as suggested by genotrance and the code that you found :)
# stdout_to_file.nim
import terminal, strformat, times
if isatty(stdout): # ./stdout_to_file
echo "This is output to the terminal."
else: # ./stdout_to_file | cat
const
logFileName = "log.txt"
let
# https://github.com/jasonrbriggs/nimwhistle/blob/183c19556d6f11013959d17dfafd43486e1109e5/tests/cgitests.nim#L15
logFile = open(logFileName, fmWrite)
stdout = logFile
echo fmt"This is output to the {logFileName} file."
echo fmt"- Run using nim {NimVersion} on {now()}."
Save above file as stdout_to_file.nim.
On running:
nim c stdout_to_file.nim && ./stdout_to_file | cat
I get this in the created log.txt:
This is output to the log.txt file.
- Run using nim 0.19.9 on 2019-01-23T22:42:27-05:00.
You should be able to use isatty().
Here's an example in Nimble.
Edit:
#tjohnson this is in response to your comment. I don't have enough points to respond to your comment directly or something? Thanks Stack Overflow...
It's hard to say without seeing more of the code.
What version of Nim are you using?
I suspect stdout has been shadowed by a read only symbol.
Are you calling this code inside of a proc and passing stdout as an argument?
like this:
proc foo(stdout: File)
If so, you will need to change it to a var parameter to make the argument writable:
proc test(stdout: var File)
Or use stdout as a global variable instead.

Can I display the log of system call in Ruby?

I need to call a command(in a sinatra or rails app) like this:
`command sub`
Some log will be outputed when the command is executing.
I want to see the log displaying continuously in the process.
But I just can get the log string after it's done with:
result = `command sub`
So, is there a way to implement this?
On windows i have the best experience with IO.popen
Here is a sample
require 'logger'
$log = Logger.new( "#{__FILE__}.log", 'monthly' )
#here comes the full command line, here it is a java program
command = %Q{java -jar getscreen.jar #{$userid} #{$password}}
$log.debug command
STDOUT.sync = true
begin
# Note the somewhat strange 2> syntax. This denotes the file descriptor to pipe to a file. By convention, 0 is stdin, 1 is stdout, 2 is stderr.
IO.popen(command+" 2>&1") do |pipe|
pipe.sync = true
while str = pipe.gets #for every line the external program returns
#do somerthing with the capturted line
end
end
rescue => e
$log.error "#{__LINE__}:#{e}"
$log.error e.backtrace
end
There's six ways to do it, but the way you're using isn't the correct one because it waits for the process the return.
Pick one from here:
http://tech.natemurray.com/2007/03/ruby-shell-commands.html
I would use IO#popen3 if I was you.

Rails Custom Logger Writes To Log Sporadically

I've set up a custom logger in an initializer:
# /config/initializers/logging.rb
log_file = File.open("#{Example::Application.config.root}/log/app.log", "a")
AppLogger = ActiveSupport::BufferedLogger.new(log_file)
AppLogger.level = Logger::DEBUG
AppLogger.auto_flushing = true
AppLogger.debug "App Logger Up"
Although it creates the log file when I start the application, it doesn't write to the log file. Either from AppLogger.debug "App Logger Up" in the initializer or similar code elsewhere in the running application.
However, intermittently I do find log statements in the file, though seemingly without any pattern. It would seem that it is buffering the log messages and dumping them when it feels like it. However I'm setting auto_flushing to true which should cause it to flush the buffer immediately.
What is going on and how can I get it working?
Note: Tailing the log with $ tail -f "log/app.log" also doesn't pick up changes.
I'm using POW, but I've also tried with WEBrick and get the same (lack of) results.
Found the answer in a comment to the accepted answer to on this question:
I added:
log_file.sync = true
And it now works.

Issues while using sqlplus with ruby

I want to use sqlplus within ruby. Dont want to use any gems[bec I cannot get it installed on our servers without much help from other teams ..etc] and want to keep it very minimal.
I am trying something as simple as this in my ruby script:
`rlwrap sqlplus user/pswd#host << EOF`
`set serveroutput on;`
`commit;` #ERROR1: sh: commit: not found
sql = "insert /*+ APPEND*/ INTO table(col1, col2) values (#{data[0]},#{data[1]});"
`#{sql}` #ERROR2: sh: Syntax error: "(" unexpected
Can anyone help me with ERROR1 and ERROR2 above
Basically for "commit: not found" I think its getting executed on shell rather than in sqlplus. However seems like "set serveroutput on" seems to execute fine !
For ERROR2, I am clueless. I also tried using escape slash for the "/" in the sql.
Thanks
The answer is, don't use SQL*Plus. Don't call a command-line utility from inside your script; between the ruby-oci8 gem and the ruby-plsql gem, you can do anything you could accomplish from within SQL*Plus.
The reason you get the errors is that you are sending each line to the shell individually. If your entire statement was wrapped in a single pair of backticks, it might work.
But if you really are unable to install the proper gems, put the commands in a temporary file and tell sqlplus to execute that, eg:
require 'tempfile'
file = Tempfile.open(['test', '.sql'])
file.puts "set serveroutput on;"
file.puts "commit;"
file.puts "insert /*+ APPEND*/ INTO table(col1, col2) values (#{data[0]},#{data[1]});"
file.puts "exit;" # needed or sqlplus will never return control to your script
file.close
output = `sqlplus user/pswd#host ##{file.path}`
file.unlink
You'll have to be very careful about:
Quoting values (if using oci8/dbi you could use bind variables)
Error handling. If using ruby libraries, errors would raise exceptions. Using sqlplus, you'll have to parse the output instead. Yuck!
So it can be done but I highly recommend you jump through whatever hoops are required to get oci8 (and maybe ruby-DBI) installed properly :)
ps are you sure you want to commit before the insert?

Strange variable-argument problem in Capistrano Task

Hello stackoverflow experts,
I got a very strange problem in a task I'm creating with Capistrano. I'm trying to pass a variable from the command line:
>> cap create_dir -s name_of_dir=mydir
task :create_dir do
printf("#{name_of_dir}")
if !(exists?(:name_of_dir)) then
name_of_dir = Capistrano::CLI.ui.ask("Name of dir to be created.")
end
full_path = "/home/#{name_of_dir}"
run "mkdir #{full_path}"
end
The very strange this is that correctly parses the variable when I do printf, but parses as a blank(empty) string in the following command. I really find no explanation for this and I'm sure is not a stuping typo or anything like that?
I'm not expierenced in Ruby like in Java and PHP, I'm affraid that there maybe a strange rule?
Thanks!!
A few suggestions:
Avoid using variables with the same name of internal task variables
use fetch() instead of dealing with if exits? else then...
Here's the code
>> cap create_dir -s name_of_dir=mydir
task :create_dir do
printf("#{name_of_dir}")
directory = fetch(:name_of_dir) { Capistrano::CLI.ui.ask("Name of dir to be created.") }
full_path = "/home/#{directory}"
run "mkdir #{full_path}"
end
In newer versions of capistrano, at least from 2.5.19 which I run now the whole command line argument thing works different now. You call it like this.
cap command argument=value
And the syntax in the code is
ENV.has_key?('argument') and ENV['argument']
That's basically it, but you can look at my blogpost about it for a working example
It looks like in the second line you are checking if the symbol :name_of_dir exists - not the actual value of the variable name_of_dir.
Because you're unlikely to have a filename name_of_dir it will count as not existing... and then name_of_dir (the variable) is overwritten by the Capistrano::CLI.ui.ask command.
Not sure why but that must be killing it somehow.
Try removing the ":" and seeing if that fixes the problem.

Resources