Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions src/main/java/org/jruby/rack/DefaultRackConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -166,12 +166,6 @@ protected RackLogger createLogger(final String loggerClass) {
throw new RackException("could not create logger: '" + loggerClass + "'", e.getTargetException());
}
}
//catch (ClassNotFoundException e) {
// if ( ! isQuiet() ) {
// err.println("failed creating logger: '" + loggerClass + "'");
// e.printStackTrace(err);
// }
//}
catch (Exception e) {
if ( ! isQuiet() ) {
err.println("failed creating logger: '" + loggerClass + "'");
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/jruby/rack/RackContext.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@
* @author nicksieger
*/
public interface RackContext extends RackLogger {
RackConfig getConfig(); /// NOTE: deprecate ?
RackConfig getConfig();
String getServerInfo();
}
4 changes: 4 additions & 0 deletions src/main/java/org/jruby/rack/RackLogger.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,8 @@ public void setLevel(Level level) { /* noop */ }
public boolean isFormatting() { return false; }
public void setFormatting(boolean flag) { /* noop */ }
}

interface DelegatingLogger extends RackLogger {
RackLogger unwrapLogger();
}
}
2 changes: 2 additions & 0 deletions src/main/java/org/jruby/rack/RackServletContextListener.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public RackServletContextListener() {
this.factory = factory;
}

@Override
public void contextInitialized(final ServletContextEvent event) {
final ServletContext context = event.getServletContext();
final ServletRackConfig config = new ServletRackConfig(context);
Expand All @@ -54,6 +55,7 @@ public void contextInitialized(final ServletContextEvent event) {
}
}

@Override
public void contextDestroyed(final ServletContextEvent event) {
final ServletContext context = event.getServletContext();
final RackApplicationFactory factory =
Expand Down
25 changes: 15 additions & 10 deletions src/main/java/org/jruby/rack/ext/Logger.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@
import org.jruby.rack.RackContext;
import org.jruby.rack.RackLogger;
import org.jruby.rack.logging.ServletContextLogger;
import org.jruby.rack.util.ExceptionUtils;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
Expand Down Expand Up @@ -123,6 +122,10 @@ public IRubyObject initialize_copy(final ThreadContext context, final IRubyObjec

@JRubyMethod
public IRubyObject real_logger(final ThreadContext context) {
RackLogger logger = this.logger;
if (logger instanceof RackLogger.DelegatingLogger) {
logger = ((RackLogger.DelegatingLogger) logger).unwrapLogger();
}
return JavaEmbedUtils.javaToRuby(context.runtime, logger);
}

Expand Down Expand Up @@ -357,8 +360,7 @@ public IRubyObject add(final ThreadContext context, final IRubyObject severity,
return context.runtime.newBoolean( add(UNKNOWN, context, msg, block) );
}

private boolean add(final int severity, final ThreadContext context,
IRubyObject msg, final Block block) {
private boolean add(final int severity, final ThreadContext context, IRubyObject msg, final Block block) {
// severity ||= UNKNOWN
final RackLogger.Level loggerLevel = mapLevel(severity);

Expand All @@ -379,10 +381,9 @@ private boolean add(final int severity, final ThreadContext context,
final long datetime = System.currentTimeMillis();
msg = format_message(context, severity, datetime, progname, msg);
}
else if ( msg instanceof RubyException ) { // print backtrace for error
final RubyException error = (RubyException) msg;
error.prepareIntegratedBacktrace(context, null);
doLog( loggerLevel, ExceptionUtils.formatError(error) );
else if ( msg instanceof RubyException ) {
final RubyException ex = (RubyException) msg;
doLog( loggerLevel, ex.toThrowable() );
return true;
}
// @logdev.write(format_message(format_severity(severity), Time.now, progname, message))
Expand Down Expand Up @@ -455,16 +456,20 @@ private static int toInt(final IRubyObject level) {
@SuppressWarnings("unchecked")
@Override
public <T> T toJava(Class<T> target) {
if ( RackLogger.class == target ) return (T) logger;
if ( RackLogger.class.isAssignableFrom(target) && target.isInstance(logger) ) return (T) logger;
return super.toJava(target);
}

private void doLog(RackLogger.Level level, Throwable ex) {
logger.log(level, "", ex);
}

private void doLog(RackLogger.Level level, CharSequence message) {
logger.log( level, message );
logger.log(level, message);
}

private void doLog(RubyString message) {
logger.log( message );
logger.log(message);
}

/**
Expand Down
7 changes: 1 addition & 6 deletions src/main/java/org/jruby/rack/logging/OutputStreamLogger.java
Original file line number Diff line number Diff line change
Expand Up @@ -113,12 +113,7 @@ public static void printLevel(final RackLogger.Base logger, final Level level, f
}

public static void printMessage(final PrintStream out, final CharSequence message) {
if ( message.charAt(message.length() - 1) == '\n' ) {
out.print(message);
}
else {
out.println(message);
}
out.println(message);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
*
* @author nicksieger
*/
public class DefaultServletRackContext implements ServletRackContext {
public class DefaultServletRackContext implements ServletRackContext, RackLogger.DelegatingLogger {

private final RackConfig config;
private final ServletContext context;
Expand Down Expand Up @@ -232,6 +232,11 @@ public void log(Level level, CharSequence message, Throwable e) {
logger.log(level, message, e);
}

@Override
public RackLogger unwrapLogger() {
return logger;
}

@Override
public int getEffectiveMajorVersion() throws UnsupportedOperationException {
return context.getEffectiveMajorVersion();
Expand Down
50 changes: 1 addition & 49 deletions src/main/java/org/jruby/rack/util/ExceptionUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,8 @@
import java.io.IOException;

import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyClass;
import org.jruby.RubyException;
import org.jruby.RubyString;
import org.jruby.exceptions.RaiseException;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;

/**
*
Expand All @@ -54,53 +49,10 @@ public static RaiseException newIOError(final Ruby runtime, final IOException ca
return raise;
}

private static RaiseException newRaiseException(final Ruby runtime,
final RubyClass errorClass, final Throwable cause) {
private static RaiseException newRaiseException(final Ruby runtime, final RubyClass errorClass, final Throwable cause) {
final String message = cause.getMessage();
RaiseException raise = RaiseException.from(runtime, errorClass, message);
raise.initCause(cause);
return raise;
}

public static CharSequence formatError(final RubyException error) {
final StringBuilder out = new StringBuilder(128);
appendError(error, out); return out;
}

private static void appendInspect(final RubyException error, final StringBuilder out) {
final RubyClass errorClass = error.getMetaClass().getRealClass();
if ( error.getMessage() != null && ! error.getMessage().isNil() ) {
out.append("#<").append( errorClass.getName() ).append(": ");
out.append( error.getMessage().asString() ).append('>');
}
else {
out.append( errorClass.getName() );
}
}

public static void appendError(final RubyException error, final StringBuilder out) {
appendInspect(error, out);
appendBacktrace(error, out.append('\n'));
}

public static void appendBacktrace(final RubyException error, final StringBuilder out) {
appendBacktrace(error, 0, out);
}

public static void appendBacktrace(final RubyException error, final int skip,
final StringBuilder out) {
final ThreadContext context = error.getRuntime().getCurrentContext();
final IRubyObject backtrace = error.callMethod(context, "backtrace");
if ( ! backtrace.isNil() ) {
final RubyArray<?> trace = backtrace.convertToArray();
out.ensureCapacity(out.length() + 24 * trace.getLength());
for ( int i = skip; i < trace.getLength(); i++ ) {
IRubyObject stackTraceLine = trace.eltInternal(i);
if ( stackTraceLine instanceof RubyString ) {
out.append("\tfrom ").append(stackTraceLine).append('\n');
}
}
}
}

}
81 changes: 74 additions & 7 deletions src/spec/ruby/jruby/rack/integration_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,9 @@

shared_examples_for 'a rails app', :shared => true do

let(:servlet_context) { new_servlet_context(base_path) }
let(:servlet_context) do
new_servlet_context(base_path).tap { |servlet_context| prepare_servlet_context(servlet_context) }
end

it "initializes pooling when min/max set" do
servlet_context.addInitParameter('jruby.min.runtimes', '1')
Expand Down Expand Up @@ -127,10 +129,66 @@
rack_factory.should be_a(RackApplicationFactory)
rack_factory.should be_a(SharedRackApplicationFactory)
rack_factory.realFactory.should be_a(RailsRackApplicationFactory)
end

rack_factory.getApplication.should be_a(DefaultRackApplication)
end

describe 'rails 7.2', lib: :rails72 do

before(:all) do name = :rails72 # copy_gemfile :
FileUtils.cp File.join(GEMFILES_DIR, "#{name}.gemfile"), File.join(STUB_DIR, "#{name}/Gemfile")
FileUtils.cp File.join(GEMFILES_DIR, "#{name}.gemfile.lock"), File.join(STUB_DIR, "#{name}/Gemfile.lock")
Dir.chdir File.join(STUB_DIR, name.to_s)
end

def base_path; "#{STUB_DIR}/rails72" end

it_should_behave_like 'a rails app'

context "initialized" do

before(:all) do
initialize_rails('production', "file://#{base_path}") do |servlet_context, _|
prepare_servlet_context(servlet_context)
end
end
after(:all) { restore_rails }

it "loaded rack ~> 2.2" do
@runtime = @rack_factory.getApplication.getRuntime
should_eval_as_not_nil "defined?(Rack.release)"
should_eval_as_eql_to "Rack.release.to_s[0, 3]", '2.2'
end

it "booted with a servlet logger" do
@runtime = @rack_factory.getApplication.getRuntime
should_eval_as_not_nil "defined?(Rails)"
should_eval_as_not_nil "Rails.logger"

# Rails 7.x wraps the default in a ActiveSupport::BroadcastLogger
should_eval_as_eql_to "Rails.logger.is_a? ActiveSupport::BroadcastLogger", true
should_eval_as_eql_to "Rails.logger.broadcasts.size", 1
should_eval_as_eql_to "Rails.logger.broadcasts.first.is_a? JRuby::Rack::Logger", true
# NOTE: TaggedLogging is a module that extends the logger instance:
should_eval_as_eql_to "Rails.logger.broadcasts.first.is_a? ActiveSupport::TaggedLogging", true

# production.rb: config.log_level = 'info'
should_eval_as_eql_to "Rails.logger.level", Logger::INFO
should_eval_as_eql_to "Rails.logger.broadcasts.first.level", Logger::INFO

unwrap_logger = "logger = Rails.logger.broadcasts.first;"
# sanity check logger-silence works:
should_eval_as_eql_to "#{unwrap_logger} logger.silence { logger.warn('from-integration-spec') }", true

should_eval_as_eql_to "#{unwrap_logger} logger.real_logger.is_a?(org.jruby.rack.logging.ServletContextLogger)", true
end

it "sets up public_path" do
@runtime = @rack_factory.getApplication.getRuntime
should_eval_as_eql_to "Rails.public_path.to_s", "#{base_path}/public"
end

end
end

def expect_to_have_monkey_patched_chunked
Expand All @@ -146,8 +204,6 @@ def expect_to_have_monkey_patched_chunked
should_eval_as_eql_to script, "1\nsecond"
end

ENV_COPY = ENV.to_h

def initialize_rails(env = nil, servlet_context = @servlet_context)
if ! servlet_context || servlet_context.is_a?(String)
base = servlet_context.is_a?(String) ? servlet_context : nil
Expand All @@ -160,19 +216,23 @@ def initialize_rails(env = nil, servlet_context = @servlet_context)
servlet_context.addInitParameter("jruby.runtime.env", the_env)

yield(servlet_context, listener) if block_given?

listener.contextInitialized javax.servlet.ServletContextEvent.new(servlet_context)
@rack_context = servlet_context.getAttribute("rack.context")
@rack_factory = servlet_context.getAttribute("rack.factory")
@servlet_context ||= servlet_context
@servlet_context = servlet_context
end

def new_servlet_context(base_path = nil)
servlet_context = org.jruby.rack.mock.RackLoggingMockServletContext.new base_path
servlet_context.logger = raise_logger
servlet_context.logger = raise_logger(:WARN).tap { |logger| logger.setEnabled(false) }
servlet_context
end

private
def prepare_servlet_context(servlet_context)
servlet_context.addInitParameter('rails.root', base_path)
servlet_context.addInitParameter('jruby.rack.layout_class', 'FileSystemLayout')
end

GEMFILES_DIR = File.expand_path('../../../gemfiles', STUB_DIR)

Expand All @@ -181,4 +241,11 @@ def copy_gemfile(name) # e.g. 'rails30'
FileUtils.cp File.join(GEMFILES_DIR, "#{name}.gemfile.lock"), File.join(STUB_DIR, "#{name}/WEB-INF/Gemfile.lock")
end

ENV_COPY = ENV.to_h

def restore_rails
ENV['RACK_ENV'] = ENV_COPY['RACK_ENV'] if ENV.key?('RACK_ENV')
ENV['RAILS_ENV'] = ENV_COPY['RAILS_ENV'] if ENV.key?('RAILS_ENV')
end

end
11 changes: 10 additions & 1 deletion src/spec/ruby/jruby/rack/logger_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
logger = JRuby::Rack::Logger.new
logger.debug?
logger.debug 'hogy basza meg a zold tucsok!'
expect( logger.real_logger ).to be rack_context
expect( logger.to_java(org.jruby.rack.RackLogger) ).to be rack_context
end

it 'delegates level check (when level is not set)' do
Expand Down Expand Up @@ -97,6 +97,15 @@
expect( real_logger.formatting? ).to be false
end

it 'logs exception with trace when passed as argument' do
begin
raise IndexError.new('TEST')
rescue => e
logger.debug(e)
end
expect( real_logger.logged_content ).to match /^DEBUG.*?IndexError.*?TEST.*?at.*?logger_spec.rb.*/m
end

it 'handles constant resolution (for Rails compatibility)' do
expect( logger.class::DEBUG ).to eql 0
expect( logger.class::FATAL ).to eql 4
Expand Down
6 changes: 6 additions & 0 deletions src/spec/stub/rails72/Rakefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.

require_relative "config/application"

Rails.application.load_tasks
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
class ApplicationController < ActionController::API
end
Empty file.
4 changes: 4 additions & 0 deletions src/spec/stub/rails72/app/controllers/sample_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
class SampleController < ApplicationController
def index
end
end
2 changes: 2 additions & 0 deletions src/spec/stub/rails72/app/helpers/sample_helper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
module SampleHelper
end
6 changes: 6 additions & 0 deletions src/spec/stub/rails72/app/models/application_record.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# class ApplicationRecord < ActiveRecord::Base
# primary_abstract_class
# end

class ApplicationRecord
end
Empty file.
2 changes: 2 additions & 0 deletions src/spec/stub/rails72/app/views/sample/index.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<h1>Sample#index</h1>
<p>Find me in app/views/sample/index.html.erb</p>
Loading
Loading